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

How to change the execution order of Javascript

醉折花枝作酒筹
Release: 2023-01-07 11:44:09
Original
3186 people have browsed it

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>
Copy after login

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();.....}
Copy after login

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);
...
}
Copy after login

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>
Copy after login

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!

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