search
HomeWeb Front-endJS TutorialDetailed 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 <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;'>&lt;script type=&quot;text/javascript&quot; language=&quot;javascript&quot;&gt; function loadjs(script_filename) { document.write(&amp;#39;&lt;&amp;#39; + &amp;#39;script language=&quot;javascript&quot; type=&quot;text/javascript&quot;&amp;#39;); document.write(&amp;#39; src=&quot;&amp;#39; + script_filename + &amp;#39;&quot;&gt;&amp;#39;); document.write(&amp;#39;&lt;&amp;#39;+&amp;#39;/script&amp;#39;+&amp;#39;&gt;&amp;#39;); alert(&quot;loadjs() exit...&quot;); } var script = &amp;#39;http://coolshell.cn/asyncjs/alert.js&amp;#39;; loadjs(script); alert(&quot;loadjs() finished!&quot;);&lt;/script&gt; &lt;script type=&quot;text/javascript&quot; language=&quot;javascript&quot;&gt; alert(&quot;another block&quot;);&lt;/script&gt;</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. &lt;p&gt;&lt;p&gt;&lt;span style=&quot;font-size: 18px;&quot;&gt;&lt;strong&gt;#script defer and async&lt;span style=&quot;color: #008000;&quot;&gt;attributes&lt;a href=&quot;http://www.php.cn/wiki/169.html&quot; target=&quot;_blank&quot;&gt;IE defer tag since IE6 , such as: &lt;p&gt;&lt;pre class='brush:php;toolbar:false;'&gt;&lt;script defer type=&quot;text/javascript&quot; src=&quot;./alert.js&quot; &gt;&lt;/script&gt;</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(&amp;#39;script&amp;#39;); script.setAttribute(&amp;#39;type&amp;#39;, &amp;#39;text/javascript&amp;#39;); script.setAttribute(&amp;#39;src&amp;#39;, script_filename); script.setAttribute(&amp;#39;id&amp;#39;, &amp;#39;coolshell_script_id&amp;#39;); script_id = document.getElementById(&amp;#39;coolshell_script_id&amp;#39;); if(script_id){ document.getElementsByTagName(&amp;#39;head&amp;#39;)[0].removeChild(script_id); } document.getElementsByTagName(&amp;#39;head&amp;#39;)[0].appendChild(script); } var script = &amp;#39;http://coolshell.cn/asyncjs/alert.js&amp;#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(&quot;http://coolshell.cn/asyncjs/alert.js&quot;)</pre><p>2) Bind to a specific event <span style="color: #008000;">(Example)<pre class='brush:php;toolbar:false;'>&lt;p style=&quot;cursor: pointer&quot; onclick=&quot;LoadJS()&quot;&gt;Click to load alert.js &lt;/p&gt;</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(&amp;#39;object&amp;#39;); cache.data = script_filename; cache.id = &quot;coolshell_script_cache_id&quot;; 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(&amp;#39;GET&amp;#39;, &amp;#39;new.js&amp;#39;); xhr.send(&amp;#39;&amp;#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!

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
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

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 the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

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 vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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 vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

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

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool