Home > Article > Web Front-end > Detailed explanation of loading and execution in JavaScript
Following the previous article "Introduction to Browser Rendering Principles", this article talks about the loading and execution of JavaScript.
Generally speaking, browsers have two major features for running JavaScript:
1) Execute immediately after loading
##2 ) will block subsequent content of the page (including page rendering and download of other resources) when executed
So, if multiple JS files are introduced, then for the browser, these JS files will be loaded serially and executed one after another. Since JavaScript may operate the DOM tree of the HTML document, browsers generally do not download JS files in parallel like they download CSS files in parallel. This is due to the particularity of JS files. Therefore, if your JavaScript wants to operate the subsequent DOM elements, the browser will report an error saying that the object cannot be found. This is because the subsequent HTML is blocked when JavaScript is executed, and there are no subsequent nodes when operating the DOM tree.The traditional way
When you write the following code:<script type="text/javascript" src="http://coolshell.cn/asyncjs/alert.js"></script>Basically , the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag in the head will block the loading of subsequent resources and the generation of the entire page. For example, in the above example, there is only one JS code (example):
alert(“hello world”) ;The effect is that a dialog box will pop up when loading this JS file, so subsequent resources will be loaded and loaded only after clicking this dialog box. Generate the entire page. So, many websites will put js at the end of the web page, or use events such as window.load, $(document).ready(function(){}). In addition, since most JavaScript code does not need to wait for the page, we need asynchronous loading function. So how do we load it asynchronously?
document.write method
You may think that the document.write() method can solve the non-blocking method. By writing the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag through the document.write method, you can execute the following things. This is true for JS code within the same script tag. However, it will still block the entire page. The following is a test code (example):<script type="text/javascript" language="javascript"> function loadjs(script_filename) { document.write('<' + 'script language="javascript" type="text/javascript"'); document.write(' src="' + script_filename + '">'); document.write('<'+'/script'+'>'); alert("loadjs() exit..."); } var script = 'http://coolshell.cn/asyncjs/alert.js'; loadjs(script); alert("loadjs() finished!");</script> <script type="text/javascript" language="javascript"> alert("another block");</script>The dialog box that pops up is:
loadjs() exit... loadjs() finished! hello world another blockThen the page will be displayed.
#script defer and asyncattributes
IE defer tag since IE6 , such as:<script defer type="text/javascript" src="./alert.js" ></script>For IE, this tag will cause IE to download the JS file in parallel, and hold its execution until the entire DOM is loaded. Multiple defer 3f1c4e4b6b16bbbd69b2ee476dc4f83a will also be executed according to Run in the order they appear. The most important thing is that after 3f1c4e4b6b16bbbd69b2ee476dc4f83a is added to the refer, it will not block subsequent DOM rendering. But because refer is only for IE, it is generally used less. Our HMTL 5 also adds an attribute for asynchronous loading of JavaScript: async. No matter what value you assign to it, as long as it appears, it will start loading the JS file asynchronously. However, async's asynchronous loading has a serious problem, that is, it faithfully executes the "execute immediately after loading" rule. Therefore, although it does not block the rendering of the page, you cannot control the order and timing of its execution (example). The browsers that support the async tag are as follows. Opera does not support it yet (from here), so this method is not very good.
How to dynamically create DOM
This method is probably the most commonly used.function loadjs(script_filename) { var script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); script.setAttribute('src', script_filename); script.setAttribute('id', 'coolshell_script_id'); script_id = document.getElementById('coolshell_script_id'); if(script_id){ document.getElementsByTagName('head')[0].removeChild(script_id); } document.getElementsByTagName('head')[0].appendChild(script); } var script = 'http://coolshell.cn/asyncjs/alert.js'; loadjs(script);This method has almost become the standard way to load js files asynchronously (example). This method also plays with jsonp stuff. That is, we can specify a background script (such as PHP) for the src of the script, and this PHP returns a JavaScript function whose parameter is a json string, which is returned to call our predefined JavaScript function. The author's reference example: t.js (This example is a small example of asynchronous ajax call that the author previously solicited on Weibo)
Asynchronous loading of JS on demand
The above DOM method example solves the problem of asynchronous loading of JavaScript, but it does not solve the problem of us wanting it to run at the timing I specify. Therefore, we need to bind the above DOM method to a certain event. For example:1) Bind to the window.load event (Example)
window.load = loadjs("http://coolshell.cn/asyncjs/alert.js")
2) Bind to a specific event (Example)
<p style="cursor: pointer" onclick="LoadJS()">Click to load alert.js </p>For example, when we click on a DOM element, our JS file will be loaded.
More
有的人可能会觉得绑定在某个特定事件上似乎过了一点,而在点击时才载入JS又太慢了。这里抛出一个终极问题:我们想要异步地把JS文件下载到用户本地,但是又不执行,仅当我们想要执行的时候才去执行。
作者提出了一种方式,就像多年之前玩preload图片那样,我们可以动用 object 标签(也可以使用 iframe 标签),于是有了下面的代码(示例):
function cachejs(script_filename){ var cache = document.createElement('object'); cache.data = script_filename; cache.id = "coolshell_script_cache_id"; cache.width = 0; cache.height = 0; document.body.appendChild(cache); }
在Chrome 下按F12(或者Ctrl+Shit+I),切换到 network页,可以看到 alert.js 文件已经下载了但是却没有执行弹出 "hello,world"对话框的操作。然后我们再用之前“绑在特定的事件上”的方式,因为浏览器端有缓存了,不会在从服务器上下载 alert.js 文件了,这样就能保证执行速度了。
我们还可以用Ajax的方式,比如:
var xhr = new XMLHttpRequest(); xhr.open('GET', 'new.js'); xhr.send('');
最后再提两个JS库,一个是ControlJS,一个叫HeadJS,专门用来做异步load javascript文件的。
来源:JavaScript 的装载和执行
The above is the detailed content of Detailed explanation of loading and execution in JavaScript. For more information, please follow other related articles on the PHP Chinese website!