Home > Article > Web Front-end > How to change the execution order of Javascript
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.
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('load',f,false); window.addEventListener('load',f1,false); ... }else{ window.attachEvent('onload',f); window.attachEvent('onload',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('<script type="text/javascript" src="test.js"><\/script>'); document.write('<script type="text/javascript" defer="defer">'); document.write('alert(2);') document.write('alert("我是" + tmpStr);'); document.write('<\/script>'); //]]> </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!