Home > Web Front-end > JS Tutorial > body text

A brief discussion on Javascript execution order_Basic knowledge

WBOY
Release: 2016-05-16 17:08:25
Original
1236 people have browsed it

Javascript is executed in a top-down order. Unless you specify otherwise, the Javascript code will not wait until the page is loaded before executing. For example, a web page contains the following HTML code:

Copy the code The code is as follows:

welcome to www.jb51.net


If you add the following Javascript code before this line of HTML code:
Copy code The code is as follows:



Run this page, you will get this error message: "document.getElementById('ele') is null." The reason is that when the above javascript is run, there is no DOM element with the ID 'ele' on the page yet.
There are two solutions:
1. Put the javascript code after the HTML code:
Copy code Code As follows:

welcome to www.jb51.net



2. Wait until the web page is loaded and run the javascript code. You can use the traditional solution (load): first add the HTML body and add "," and then call the above javascript code in the load() function. What I want to focus on here is to use jQuery to achieve it:
Copy the code The code is as follows:

< ;script>
$(document).ready(function(){
document.getElementById('ele').innerHTML= 'welcome to my blog';
});

//Of course, since jQuery is used, the simpler way to write it is:
<script><br>$(document).ready(function(){<br> $('#ele' ).html('welcome to my blog'); //The .text() method is also available here<br>});<br></script>

You can put the above jQuery No matter where the code is placed on the page, it will always wait until the page is loaded before executing.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template