search
HomeWeb Front-endJS TutorialSummary of JS synchronization, asynchronous and lazy loading implementation

This time I will bring you a summary of the implementation of JS synchronization, asynchronous and delayed loading, and what are the precautions for the implementation of JS synchronization, asynchronous and delayed loading. The following is a practical case, let's take a look.

1: Synchronous loading

The most commonly used method.

<script src="http://yourdomain.com/script.js"></script>

Synchronous mode, also known as blocking mode , will prevent the browser from subsequent processing and stop subsequent parsing. Only when the current loading is completed, the next step can be performed. Therefore, synchronous execution is safe by default. But if there are behaviors such as outputting document content, modifying DOM, redirection, etc. in js, it will cause page congestion. Therefore, it is generally recommended to place the <script> tag at the end of <body> to reduce page blocking as much as possible. </script>

2: Asynchronous loading

Asynchronous loading is also called non-blocking loading. While the browser is downloading and executing js, it will continue to process subsequent pages. There are three main ways.

Method 1: Also called Script DOM Element

(function(){
 var scriptEle = document.createElement("script");
 scriptEle.type = "text/javasctipt";
 scriptEle.async = true;
 scriptEle.src = "http://cdn.bootcss.com/jquery/3.0.0-beta1/jquery.min.js";
 var x = document.getElementsByTagName("head")[0];
 x.insertBefore(scriptEle, x.firstChild); 
 })();

attribute is a new asynchronous support in HTML5. This method is called the Script DOM Element method. Both Google Analytics and Google Badge use this asynchronous loading code.

(function(){;
 var ga = document.createElement('script'); 
 ga.type = 'text/javascript'; 
 ga.async = true; 
 ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; 
 var s = document.getElementsByTagName('script')[0]; 
 s.parentNode.insertBefore(ga, s); 
})();

However, this loading method will prevent the onload event from being triggered before the execution is completed. Now, the code of many pages also performs additional rendering work during onload, so it will still block the initialization processing of some pages.

Method 2: Asynchronous loading during onload

(function(){
 if(window.attachEvent){
 window.attachEvent("load", asyncLoad);
 }else{
 window.addEventListener("load", asyncLoad);
 }
 var asyncLoad = function(){
 var ga = document.createElement('script'); 
 ga.type = 'text/javascript'; 
 ga.async = true; 
 ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; 
 var s = document.getElementsByTagName('script')[0]; 
 s.parentNode.insertBefore(ga, s);
 }
)();

This method just puts the method of inserting script in a function, and then puts it in the onload method of the window Execution, thus solving the problem of blocking the onload event triggering.

Note: The difference between DOMContentLoaded and load. The former is after the document has been parsed and the DOM elements in the page are available, but the pictures, videos, audio and other resources in the page have not been loaded. The function is the same as the ready event in jQuery; the difference in the latter is that all resources on the page have been loaded.

Method 3: Other methods

Due to the dynamic nature of JavaScript, there are many asynchronous loading methods: XHR Injection, XHR Eval, Script In Iframe, Script defer attribute, document.write(script tag).

XHR Injection (XHR injection): Get javascript through XMLHttpRequest, and then create a script element to insert into the DOM structure. After the ajax request is successful, set script.text to the responseText returned after the request is successful.

 //获取XMLHttpRequest对象,考虑兼容性。
 var getXmlHttp = function(){
 var obj;
 if (window.XMLHttpRequest)
  obj = new XMLHttpRequest();
 else
  obj = new ActiveXObject("Microsoft.XMLHTTP");
 return obj;
 }; 
 //采用Http请求get方式;open()方法的第三个参数表示采用异步(true)还是同步(false)处理
 var xmlHttp = getXmlHttp();
 xmlHttp.open("GET", "http://cdn.bootcss.com/jquery/3.0.0-beta1/jquery.min.js", true);
 xmlHttp.send(); 
 xmlHttp.onreadystatechange = function(){
 if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
  var script = document.createElement("script");
  script.text = xmlHttp.responseText;
  document.getElementsByTagName("head")[0].appendChild(script);
 }
 }

XHR Eval: Different from the way XHR Injection executes responseText, responseText is directly executed in the eval() function.

//获取XMLHttpRequest对象,考虑兼容性。
 var getXmlHttp = function(){
 var obj;
 if (window.XMLHttpRequest)
  obj = new XMLHttpRequest();
 else
  obj = new ActiveXObject("Microsoft.XMLHTTP");
 return obj;
 }; 
 //采用Http请求get方式;open()方法的第三个参数表示采用异步(true)还是同步(false)处理
 var xmlHttp = getXmlHttp();
 xmlHttp.open("GET", "http://cdn.bootcss.com/jquery/3.0.0-beta1/jquery.min.js", true);
 xmlHttp.send(); 
 xmlHttp.onreadystatechange = function(){
 if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
  eval(xmlHttp.responseText);
  //alert($);//可以弹出$,表明JS已经加载进来。click事件放在其它出会出问题,应该是还没加载进来
  $("#btn1").click(function(){
  alert($(this).text());
  });
 }
 }

Script In Irame: Insert an iframe element in the parent window, and then perform the operation of loading JS in the iframe.

 var insertJS = function(){alert(2)};
 var iframe = document.createElement("iframe");
 document.body.appendChild(iframe);
 var doc = iframe.contentWindow.document;//获取iframe中的window要用contentWindow属性。
 doc.open();
 doc.write("<script>var insertJS = function(){};<\/script><body onload=&#39;insertJS()&#39;></script>

The above is the detailed content of Summary of JS synchronization, asynchronous and lazy loading implementation. 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 in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

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.

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.

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

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools