Home >Web Front-end >JS Tutorial >A brief introduction to JavaScript execution order

A brief introduction to JavaScript execution order

黄舟
黄舟Original
2017-03-14 15:12:431518browse

This is an article about the basics of JavaScript. It mainly explains the order in which JavaScript is executed after the web page is loaded. This is very important for us to understand the running mechanism of JavaScript. Let’s take a look. .

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:

<p id="ele">welcome to www.codeceo.com</p>

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

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

When you run the page, you will get an error like this 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. Place the javascript code after the HTML code:

<p id="ele">welcome to www.codeceo.com</p>

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

<script>
$(document).ready(function(){
   document.getElementById(&#39;ele&#39;).innerHTML= &#39;welcome to my blog&#39;;
});
</script>
//当然,既然用到了jQuery,更简单的写法是:
<script>
$(document).ready(function(){
   $(&#39;#ele&#39;).html(&#39;welcome to my blog&#39;); //这里也可用.text()方法
});
</script>

You can place the above jQuery code anywhere on the page, and it will always wait until the page is loaded before executing.

The above is the detailed content of A brief introduction to JavaScript execution order. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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