Summary of common ways to load JavaScript script files in html
When the browser encounters the (embedded) <script> tag, the current browser has no way of knowing whether JavaScript will modify the page content. Therefore, the browser will stop processing the page at this time, first execute the javaScript code, and then continue to parse and render the page. The same situation also occurs in the process of using the src attribute to add javaScript (that is, external link javaScript). The browser must first spend time downloading the code in the external link file, and then parse and execute it. During this process, page rendering and user interaction are completely blocked. </script>
In other words: whenever the browser parses the <script> tag (whether embedded or external link), the browser will (singlely) prioritize downloading and parsing And execute the javaScript code in the tag, blocking the download and rendering of all subsequent page content. </script>
Method 1: Conventional approach
The most traditional way is to insert <script> in the head tag Label. </script>
However, this conventional approach hides serious performance problems. According to the above description of the characteristics of the <script> tag, we know that in this example, when the browser parses the <script> tag, the browser will stop parsing the content after it, and give priority to downloading the script file and executing it. The code in it means that the subsequent test.css style file and the <body> tag cannot be loaded. Since the <body> tag cannot be loaded, the page cannot be rendered. Therefore, the page will be blank until the javaScript code is completely executed. </script>
<script type="text/javaScript" src="example.js"></script>
Method 2: Classic approach
##Since the <script> tag will block the loading of subsequent content , then wouldn’t it be possible to avoid this bad situation by placing the <script> tag after all page content? Place all <script> tags as close to the bottom of the <body> tag as possible to minimize impact on the download of the rest of the page. <p> Parallel downloading of scripts has been implemented on IE8+ browsers, but in some browsers (even if the script file is placed at the bottom of the <body> tag), the scripts in the page are still loaded one after another. So we need the next method, which is: dynamically loading scripts. <p><p>Method 3: <strong><span style="color: #800000">Dynamic script<strong>Through the Document Object Model (DOM), we can almost anywhere on the page create. <p><p class="jb51code">##<pre class='brush:php;toolbar:false;'><script type=&#39;text/javascript&#39;> var script = document.createElement(&#39;script&#39;); script.type = &#39;text/javaScript&#39;; script.src = &#39;file1.js&#39;; document.getElementsByTagName(&#39;head&#39;)[0].appendChild(script); </script></pre><br/>The above code dynamically creates a <script> tag of external link file1 and adds it to the <head> tag. The key point of this technology is: <p>No matter when the download is started, the download and execution process of the file will not block other processes on the page (including script loading). However, this method is also flawed. The script loaded by this method will be executed immediately after the download is completed, which means that the running order between multiple scripts cannot be guaranteed (except for Firefox and Opera). When a script has a dependency on another script, errors are likely to occur. For example, to write a jQuery code, you need to import the jQuery library. However, the jQuery code file you write will most likely be downloaded first and executed immediately. At this time, the browser will report an error - 'jQuery is not defined' or the like, because jQuery is not defined at this time. The library has not been downloaded yet. So the following improvements were made: <p><br/><p class="jb51code"><pre class='brush:php;toolbar:false;'><script type=&#39;text/javascript&#39;> function loadScript(url, callback) { var script = document.createElement(&#39;script&#39;); script.type = "text/javaScript"; // IE和opera支持onreadystatechange // safari、chrome、opera支持onload if (script.readyState) {//IE script.onreadystatechange = function() { if (script.readyState == "loaded" || script.readyState == "complete") { script.onreadystatechange = null; callback(); } }; } else {//其他浏览器 script.onload = function() { callback(); }; } script.src = url; document.getElementsByTagName(&#39;head&#39;)[0].appendChild(script); } </script></pre><br/>The improvement in the above code is to add a callback function, which will be called after the corresponding script file is loaded. In this way, sequential loading can be achieved. The writing is as follows (assuming that file2 depends on file1, and file1 and file3 are independent of each other): <pre class='brush:php;toolbar:false;'>loadScript(‘file1.js&#39;,function(){ loadScript(‘file2.js&#39;,function(){}); }); loadScript(‘file3.js&#39;,function(){});</pre><p>file2 will start loading after file1 is loaded, ensuring that file1 has been prepared before file2 is executed. appropriate. File1 and file3 are downloaded in parallel and do not affect each other. Although the loadScript function is good enough, there are still some unsatisfactory aspects - by analyzing this code, we know that the sequential loading in the loadScript function is implemented by blocking loading of the script (as pointed out in the red text above) . What we really want to achieve is - the scripts are downloaded synchronously and executed in the corresponding order, that is, loaded in parallel and executed sequentially. </script>The above is the detailed content of Summary of common ways to load JavaScript script files in html. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

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.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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

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