Home >Web Front-end >JS Tutorial >How to change the execution order of Javascript

How to change the execution order of Javascript

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-07-19 14:45:563201browse

Method: 1. Use onload; 2. You can use deferdefer in IE to load the code and not execute it immediately. It will be executed after the document is loaded; 3. Use xmlhttpRequest in Ajax to determine the external document Loading status.

How to change the execution order of Javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

1. Use onload

<script type="text/javascript">
//<![CDATA[
window.onload = f;
function f(){alert(1);}
alert(2);
//]]>
</script>

The order of output values ​​is 2, 1.

It should be noted that if there are multiple winodws.onload, only the most effective one will take effect. The solution is:

window.onload = function(){f();f1();f2();.....}

Use the level 2 DOM event type

if(document.addEventListener){
window.addEventListener(&#39;load&#39;,f,false);
window.addEventListener(&#39;load&#39;,f1,false);
...
}else{
window.attachEvent(&#39;onload&#39;,f);
window.attachEvent(&#39;onload&#39;,f1);
...
}

2. Deferdefer can be used in IE to load the code and not execute it immediately. It will be executed after the document is loaded. It is somewhat similar to onload, but it does not have the limitations of onload. It can be reused, but it is only effective in IE. , so the above example can be modified to

<script type="text/javascript">
//<![CDATA[
document.write(&#39;<script type="text/javascript" src="test.js"><\/script>&#39;);
document.write(&#39;<script type="text/javascript" defer="defer">&#39;);
document.write(&#39;alert(2);&#39;)
document.write(&#39;alert("我是" + tmpStr);&#39;);
document.write(&#39;<\/script>&#39;);
//]]>
</script>
<script type="text/javascript">
//<![CDATA[
alert(3);
//]]>
</script>

so that IE will not report an error, and the order of output values ​​becomes: 1, 3, 2, I am 1

3, using Ajax.

Because xmlhttpRequest can determine the loading status of external documents, it can change the loading order of the code.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to change the execution order of Javascript. 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