Talk about Javascript execution order

  • 2020-03-30 00:57:47
  • OfStack

Javascript is executed from the top down, and unless you specify otherwise, Javascript code doesn't wait until the page loads. For example, a web page contains the following HTML code:

<div id="ele">welcome to www.jb51.net</div>

If you add the following Javascript code before this line of HTML code:

<script type="text/javascript">
  document.getElementById('ele').innerHTML= 'welcome to my blog';
</script>

Run the page and you'll get an error message like this: "document.getelementbyid (' ele') is null." The reason is that when the javascript above runs, there is no DOM element with the ID 'ele' on the page.
There are two solutions:
1. Put the javascript code after the HTML code:

 <div id="ele">welcome to www.jb51.net</div>
<script type="text/javascript">
  document.getElementById('ele').innerHTML='welcome to my blog';
</script>

2. Wait until the page is loaded and run the javascript code. You can use the traditional solution (load) : first add the body of the HTML and add "< The body load = "load ()" > Then call the above javascript code in the load() function. Here is the emphasis on using jQuery to implement:

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

You can put the above jQuery code anywhere on the page, it always waits until the page is loaded.

Related articles: