Home >Web Front-end >JS Tutorial >How to ensure the execution order of JavaScript - Practical Chapter_javascript skills

How to ensure the execution order of JavaScript - Practical Chapter_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:09:591016browse
1. Introduction
I mentioned the sequential execution feature of JavaScript at the end of the article "How to use the same HTML fragment on multiple pages - continued". Although modern browsers can download JavaScript in parallel (some browsers), considering the dependencies of JavaScript, their execution is still carried out in the order of introduction.
In order to better test this process, I wrote a simple HTTP handler page service.ashx, which can accept two parameters:
1. file, which needs to return the server-side path of the file.
2. delay, delay for a certain period of time before returning this HTTP request (milliseconds).
A typical page such as: ./service.ashx?file=js/jquery-ui.js&delay=2000 means a delay of 2 seconds before returning to the js/jquery-ui.js file on the server side.
The key code of service.ashx is as follows:
Copy code The code is as follows:

public void ProcessRequest(HttpContext context)
{
int delay = 0;
if (!String.IsNullOrEmpty(context.Request["delay"]))
{
delay = Convert.ToInt32 (context.Request["delay"]);
}
if (delay > 0)
{
System.Threading.Thread.Sleep(1000);
}
string filePath = context.Request["file"].ToString();
string fileContent = String.Empty;
using (StreamReader sr = new StreamReader(context.Server.MapPath(filePath)))
{
fileContent = sr.ReadToEnd();
}
if (filePath.EndsWith(".js"))
{
context.Response.ContentType = "application/x-javascript ";
}
else
{
context.Response.ContentType = "text/plain";
}
context.Response.Write(fileContent);
}

2. Directly introduce JavaScript (test1.htm) through the script tag.
First, let’s analyze the situation of sequentially introducing JavaScript in the tag. The page source code of test1.htm is as follows:
Copy code The code is as follows:





<script> <br>function addScript(url, inline) { <br>var head = document.getElementsByTagName("head")[0]; <br>var script = document.createElement ('script'); <br>script.type = 'text/javascript'; <br>if (inline) { <br>script.text = url; <br>} else { <br>script.src = url ; <br>} <br>head.appendChild(script); <br>} <br>$(function () { <br>addScript('./service.ashx?file=js/jquery-ui.js&delay= 2000'); <br>addScript('alert(typeof(jQuery.ui));', true); <br>}); <br></script>







我们分别在各种浏览器中测试这个例子:
test3.htm
通过JavaScript添加<script>标签 <br> <table style="BORDER-RIGHT: medium none; BORDER-TOP: medium none; MARGIN-LEFT: 10.5pt; BORDER-LEFT: medium none; WIDTH: 413.1pt; BORDER-BOTTOM: medium none; BORDER-COLLAPSE: collapse" cellspacing="0" cellpadding="0" width="689" border="1"> <tbody> <tr> <td style="BORDER-RIGHT: 1pt solid; PADDING-RIGHT: 5.4pt; BORDER-TOP: medium none; PADDING-LEFT: 5.4pt; PADDING-BOTTOM: 0cm; BORDER-LEFT: 1pt solid; WIDTH: 67.25pt; PADDING-TOP: 0cm; BORDER-BOTTOM: 1pt solid" valign="top" width="112"> <p align="left"><span>Firefox 3.6</span></p> </td> <td style="BORDER-RIGHT: 1pt solid; PADDING-RIGHT: 5.4pt; BORDER-TOP: medium none; PADDING-LEFT: 5.4pt; PADDING-BOTTOM: 0cm; BORDER-LEFT: medium none; WIDTH: 345.85pt; PADDING-TOP: 0cm; BORDER-BOTTOM: 1pt solid" valign="top" width="576"> <p align="left"><img style="max-width:90%" alt="" src="http://files.jb51.net/upload/201103/20110303231405311.gif" style="max-width:90%" border="0"></p> </td> </tr> <tr> <td style="BORDER-RIGHT: 1pt solid; PADDING-RIGHT: 5.4pt; BORDER-TOP: medium none; PADDING-LEFT: 5.4pt; PADDING-BOTTOM: 0cm; BORDER-LEFT: 1pt solid; WIDTH: 67.25pt; PADDING-TOP: 0cm; BORDER-BOTTOM: 1pt solid" valign="top" width="112"> <p align="left">IE 8</p> </td> <td style="BORDER-RIGHT: 1pt solid; PADDING-RIGHT: 5.4pt; BORDER-TOP: medium none; PADDING-LEFT: 5.4pt; PADDING-BOTTOM: 0cm; BORDER-LEFT: medium none; WIDTH: 345.85pt; PADDING-TOP: 0cm; BORDER-BOTTOM: 1pt solid" valign="top" width="576"> <p align="left"><img style="max-width:90%" alt="" src="http://files.jb51.net/upload/201103/20110303231407246.gif" style="max-width:90%" border="0"></p> </td> </tr> <tr> <td style="BORDER-RIGHT: 1pt solid; PADDING-RIGHT: 5.4pt; BORDER-TOP: medium none; PADDING-LEFT: 5.4pt; PADDING-BOTTOM: 0cm; BORDER-LEFT: 1pt solid; WIDTH: 67.25pt; PADDING-TOP: 0cm; BORDER-BOTTOM: 1pt solid" valign="top" width="112"> <p align="left"><span>Chrome 10</span></p> </td> <td style="BORDER-RIGHT: 1pt solid; PADDING-RIGHT: 5.4pt; BORDER-TOP: medium none; PADDING-LEFT: 5.4pt; PADDING-BOTTOM: 0cm; BORDER-LEFT: medium none; WIDTH: 345.85pt; PADDING-TOP: 0cm; BORDER-BOTTOM: 1pt solid" valign="top" width="576"> <p align="left"><img style="max-width:90%" alt="" src="http://files.jb51.net/upload/201103/20110303231407150.gif" style="max-width:90%" border="0"></p> </td> </tr> <tr> <td style="BORDER-RIGHT: 1pt solid; PADDING-RIGHT: 5.4pt; BORDER-TOP: medium none; PADDING-LEFT: 5.4pt; PADDING-BOTTOM: 0cm; BORDER-LEFT: 1pt solid; WIDTH: 67.25pt; PADDING-TOP: 0cm; BORDER-BOTTOM: 1pt solid" valign="top" width="112"> <p align="left"><span>Safari 4</span></p> </td> <td style="BORDER-RIGHT: 1pt solid; PADDING-RIGHT: 5.4pt; BORDER-TOP: medium none; PADDING-LEFT: 5.4pt; PADDING-BOTTOM: 0cm; BORDER-LEFT: medium none; WIDTH: 345.85pt; PADDING-TOP: 0cm; BORDER-BOTTOM: 1pt solid" valign="top" width="576"> <p align="left"><img style="max-width:90%" alt="" src="http://files.jb51.net/upload/201103/20110303231407465.jpg" style="max-width:90%" border="0"></p> </td> </tr> <tr> <td style="BORDER-RIGHT: 1pt solid; PADDING-RIGHT: 5.4pt; BORDER-TOP: medium none; PADDING-LEFT: 5.4pt; PADDING-BOTTOM: 0cm; BORDER-LEFT: 1pt solid; WIDTH: 67.25pt; PADDING-TOP: 0cm; BORDER-BOTTOM: 1pt solid" valign="top" width="112"> <p align="left"><span>Opera 11</span></p> </td> <td style="BORDER-RIGHT: 1pt solid; PADDING-RIGHT: 5.4pt; BORDER-TOP: medium none; PADDING-LEFT: 5.4pt; PADDING-BOTTOM: 0cm; BORDER-LEFT: medium none; WIDTH: 345.85pt; PADDING-TOP: 0cm; BORDER-BOTTOM: 1pt solid" valign="top" width="576"> <p align="left"><img style="max-width:90%" alt="" src="http://files.jb51.net/upload/201103/20110303231406793.gif" style="max-width:90%" border="0"></p> </td> </tr> </tbody> </table></span></p> <p align="left"><span style="FONT-FAMILY: 宋体">It can be seen that when </span>JavaScript<span style="FONT-FAMILY: 宋体"> is introduced after </span>DOM<span style="FONT-FAMILY: 宋体"> is loaded and then external or inline </span>JavaScript<span style="FONT-FAMILY: 宋体"> is introduced, </span>Firefox<span style="FONT-FAMILY: 宋体"> and The behavior of </span>Opera<span style="FONT-FAMILY: 宋体"> is consistent, ensuring that the execution order of </span>JavaScript<span style="FONT-FAMILY: 宋体"> is consistent with the order of introduction. However, </span>IE8, Chrome, Safari <span style="FONT-FAMILY: 宋体"> cannot guarantee this execution order. </span></p> <p><span style="FONT-FAMILY: 宋体">Although various browsers differ in ensuring the order of execution, the biggest benefit at this time is that multiple </span>JavaScript<span style="FONT-FAMILY: 宋体"> files can be downloaded in parallel, which behaves consistently across all browsers. Of course this is not the topic of this article, you can </span><a href="http://www.google.com/search?q=javascript%20parallel%20download">Google<span style="FONT-FAMILY: 宋体"><span> for more details</span></span></a><span style="FONT-FAMILY: 宋体">. </span></p> <p><span style="FONT-FAMILY: 宋体">How to solve the inconsistency between browsers, two solutions are provided below: <br><strong>4. Solution 1, how to ensure the execution order when dynamically adding script tags <br></strong> Sometimes the page logic requires us to dynamically execute JavaScript through the above method, so how to ensure the execution order under all browsers (currently only Firefox and Opera ensure the execution order). <br>In fact, the solution is very simple. We just add a complete callback function for function execution. The following test4.htm gives a specific solution: <br><div class="codetitle"> <span><a style="CURSOR: pointer" data="768" class="copybut" id="copybut768" onclick="doCopy('code768')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code768"> <br><html> <br><head> <br><title></title> <br><script src="./js/jquery-1.4.4.js" type="text/ javascript"></script>
<script> <br>function addScript(url, inline, callback) { <br>var head = document.getElementsByTagName("head")[0]; <br> var script = document.createElement('script'); <br>script.type = 'text/javascript'; <br>if (inline) { <br>script.text = url; <br>} else { <br>script.src = url; <br>script.onload = script.onreadystatechange = function () { <br>if (!script.readyState || script.readyState === 'loaded' || script.readyState === 'complete') { <br>if (callback) { <br>callback(); <br>} <br>script.onload = script.onreadystatechange = null; <br>}; <br>}; <br> } <br>head.appendChild(script); <br>if (inline && callback) { <br>callback(); <br>} <br>} <br>$(function () { <br>addScript( './service.ashx?file=js/jquery-ui.js&delay=2000', false, function () { <br>addScript('alert(typeof(jQuery.ui));', true); <br> }); <br>}); <br></script>



< /div>



此时所有浏览器中的行为一致:
test4.htm
通过回调函数解决动态添加JavaScript的顺序问题

Firefox 3.6

IE 8

Chrome 10

Safari 4

Opera 11


5. 方案二,使用jQuery的html函数动态添加JavaScript
jQuery的html函数用来更新一个DOM片段,我们可以很方便的通过这个函数来动态加载JavaScript,请看示例test2.htm:
复制代码 代码如下:





<script> <br>$(function(){ <br>$('#container').html('<script src="./service.ashx?file=js/jquery-ui.js&delay=2000" type="text\/javascript"><\/script>' + '<script>alert(typeof(jQuery.ui));<\/script>'); <br>}); <br></script>







此时,各个浏览器中的行为一致:
test2.htm
通过jQuery的html函数解决动态添加JavaScript的顺序问题

Firefox 3.6

IE 8

Chrome 10

Safari 4

Opera 11


6. 포스트스크립트
jQuery의 html 함수는 왜 동적으로 로드되는 JavaScript의 실행 순서를 보장할 수 있나요?
단순히 .innerHTML로 DOM 노드를 업데이트하면 그 안에 있는 JavaScript가 실행되지 않는다는 것을 알고 있습니다. 이 예제의 소스 코드를 다음과 같이 간단히 변경할 수 있습니다.
$('#container')[0] .innerHTML = ' '<script>경고( typeof(jQuery.ui));</script>'
이 경우 jQueryUI가 전혀 로드되지 않습니다.
그럼 jQuery는 어떻게 작동하나요? 다음 기사에서는 소스를 추적하고 jQuery 소스 코드를 자세히 분석할 예정입니다. 계속해서 살펴보세요. JavaScript의 실행 순서를 확인하는 방법 – jQuery.html 심층 분석

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