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 <script> 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): <p><pre class='brush:php;toolbar:false;'>alert(“hello world”) ;</pre>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. <p>So, many websites will put js at the end of the web page, or use events such as window.load, $(document).ready(function(){}). <p>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? <p><p><span style="font-size: 18px;"><strong>document.write method <span style="color: #008000;">You may think that the document.write() method can solve the non-blocking method. By writing the <script> 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): <p><pre class='brush:php;toolbar:false;'><script type="text/javascript" language="javascript"> function loadjs(script_filename) { document.write(&#39;<&#39; + &#39;script language="javascript" type="text/javascript"&#39;); document.write(&#39; src="&#39; + script_filename + &#39;">&#39;); document.write(&#39;<&#39;+&#39;/script&#39;+&#39;>&#39;); alert("loadjs() exit..."); } var script = &#39;http://coolshell.cn/asyncjs/alert.js&#39;; loadjs(script); alert("loadjs() finished!");</script> <script type="text/javascript" language="javascript"> alert("another block");</script></pre>The dialog box that pops up is: <p><pre class="brush:php;toolbar:false">loadjs() exit... loadjs() finished! hello world another blockThen the page will be displayed. <p><p><span style="font-size: 18px;"><strong>#script defer and async<span style="color: #008000;">attributes<a href="http://www.php.cn/wiki/169.html" target="_blank">IE defer tag since IE6 , such as: <p><pre class='brush:php;toolbar:false;'><script defer type="text/javascript" src="./alert.js" ></script></pre> 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 <script> will also be executed according to Run in the order they appear. The most important thing is that after <script> is added to the refer, it will not block subsequent DOM rendering. But because refer is only for IE, it is generally used less. <p>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). <p>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. <p><p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/010/da6d04724b6a8d2a4de7ae144c102836-0.png?x-oss-process=image/resize,p_40" class="lazy" alt=""/> <p><p><span style="max-width:90%"><strong>How to dynamically create DOM<span style="color: #008000;"> This method is probably the most commonly used. <p><pre class='brush:php;toolbar:false;'>function loadjs(script_filename) { var script = document.createElement(&#39;script&#39;); script.setAttribute(&#39;type&#39;, &#39;text/javascript&#39;); script.setAttribute(&#39;src&#39;, script_filename); script.setAttribute(&#39;id&#39;, &#39;coolshell_script_id&#39;); script_id = document.getElementById(&#39;coolshell_script_id&#39;); if(script_id){ document.getElementsByTagName(&#39;head&#39;)[0].removeChild(script_id); } document.getElementsByTagName(&#39;head&#39;)[0].appendChild(script); } var script = &#39;http://coolshell.cn/asyncjs/alert.js&#39;; loadjs(script);</pre>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) <p><p><span style="font-size: 18px;"><strong>Asynchronous loading of JS on demand<span style="color: #008000;">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. <p>For example: <p><p>1) Bind to the window.load event <span style="color: #008000;"> (Example) <pre class='brush:php;toolbar:false;'>window.load = loadjs("http://coolshell.cn/asyncjs/alert.js")</pre><p>2) Bind to a specific event <span style="color: #008000;">(Example)<pre class='brush:php;toolbar:false;'><p style="cursor: pointer" onclick="LoadJS()">Click to load alert.js </p></pre>For example, when we click on a DOM element, our JS file will be loaded. <p><p><span style="font-size: 18px;"><strong>More<span style="color: #008000;"><p>有的人可能会觉得绑定在某个特定事件上似乎过了一点,而在点击时才载入JS又太慢了。这里抛出一个终极问题:<span style="color: #008000;">我们想要异步地把JS文件下载到用户本地,但是又不执行,仅当我们想要执行的时候才去执行。<p>作者提出了一种方式,就像多年之前玩preload图片那样,我们可以动用 object 标签(也可以使用 iframe 标签),于是有了下面的代码(示例):<pre class='brush:php;toolbar:false;'>function cachejs(script_filename){ var cache = document.createElement(&#39;object&#39;); cache.data = script_filename; cache.id = "coolshell_script_cache_id"; cache.width = 0; cache.height = 0; document.body.appendChild(cache); }</pre><p>在Chrome 下按F12(或者Ctrl+Shit+I),切换到 network页,可以看到 alert.js 文件已经下载了但是却没有执行弹出 "hello,world"对话框的操作。然后我们再用之前“绑在特定的事件上”的方式,因为浏览器端有缓存了,不会在从服务器上下载 alert.js 文件了,这样就能保证执行速度了。<p>我们还可以用Ajax的方式,比如:<pre class='brush:php;toolbar:false;'>var xhr = new XMLHttpRequest(); xhr.open(&#39;GET&#39;, &#39;new.js&#39;); xhr.send(&#39;&#39;);</pre><p>最后再提两个JS库,一个是ControlJS,一个叫HeadJS,专门用来做异步load javascript文件的。<p>来源:JavaScript 的装载和执行</script>
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!

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool