This time I will bring you a summary of the use of JS loading method, what are the precautions when using JS loading method, 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); })();
(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='insertJS()'></script>
The above is the detailed content of JS loading method usage summary. For more information, please follow other related articles on the PHP Chinese website!

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

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.


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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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.

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

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

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