search
HomeWeb Front-endJS TutorialAnalysis of Javascript loading

Analysis of Javascript loading

Jul 11, 2018 am 10:36 AM

This article mainly introduces the analysis of Javascript loading, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

1. Browser loading

(1) Synchronous loading

In a web page, the way the browser loads js files is through the <script> tag. As shown below: </script>

//内嵌脚本
<script type="text/javacript">    
// code here!
</script>
//加载外部脚本
<script type="text/javascript src="path/demo.js"></script>

<script> tag is very convenient. As long as it is added, the browser can read and run it. However, when reading, the browser follows the appearance of the <script> tag. Sequentially, Javascript files are read and then run immediately. As a result, when multiple files depend on each other, the file with the smallest dependency must be placed at the front and the file with the greatest dependency must be placed at the end. Otherwise, the code will report an error. , I believe everyone has a deep understanding of it when using bootstrap. On the other hand, browsers load the <script> tag in synchronous mode, which means that the page waits for the JavaScript file to be loaded before running the subsequent code. When there are many <script> tags, the browser cannot read them at the same time. It must read one and then the other, which causes the reading time to be greatly extended, the page response is slow, and the user experience is affected. 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 can the next operation be performed, so 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 blocking. Therefore, it is generally recommended to place the <script> tag at the end of <body>, which can reduce page blocking. </script>

(2) Asynchronous loading

In order to solve this problem, ES5 uses the DOM method to dynamically load JavaScript script files.

function loadScript(url) {    
var script = document.createElement("script");
    script.type="text/javascript";
    script.src=url;
    document.body.appendChild(script);
}

This method creates a new <script> tag and sets its src attribute to read the javacript file asynchronously</script>

This will not cause page blocking, but there will be another The problem is, if other script files depend on it, there is no guarantee when this script will be loaded.

Another loading method is to use the defer and async attributes to make the script load asynchronously. When the rendering engine encounters this line of command, it will start to download the external script, but will not wait for it to be downloaded and executed, but will directly execute the following commands. The difference between defer and async is: defer will not be executed until the entire page is rendered normally in memory (the DOM structure is completely generated and other scripts are executed); async once the download is completed, the rendering engine will interrupt the rendering and execute this script Later, continue rendering. That is, defer is executed after rendering, and async is executed after downloading. In addition, if there are multiple defer scripts, they will be loaded in the order in which they appear on the page, while multiple async scripts cannot guarantee the loading order.

# EE9 and below have some quite bad errors in the delay implementation, resulting in the order of execution cannot be guaranteed. If you need to support

<script></script>
<script></script>

How to choose defer and async. If the script used is a module and does not depend on any other script files, use async; if the script depends on other scripts or is dependent on other scripts, use defer; if the script file is small and is dependent on an async script, use internal Embed script puts this file in front of all async scripts.

Another method is asynchronous loading of the onload event.

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

This method is to put the method of inserting the script in a function, and then execute it in the onload method of the window. This solves the problem of blocking the triggering of the onload event.

Due to the dynamic nature of Javascript, there are many asynchronous loading methods: XHR Injection, XHR eval, Script In Iframe, document.write("

var createXHR  = function() {
    var obj;
    if(window.XMLHttpRequest)
        obj = new XMLHttpRequest();
    else
        obj = new ActiveObject("Microsoft.XMLHTTP");
    return obj;
};
var xhr = createXML();
xhr.open("GET", "http://cdn.bootcss.com/jquery/3.0.0-beta1/jquery.min.js", true);
xhr.send();
xhr.onreadystatechange = function() {
    if(xhr.readyState == 4 && xhr.status == 200) {
        var script = document.createElement("script");
        script.text = xhr.requestText;
        document.getElementsByTagName("head")[0].appendChild(script);
    }
}

XHR eval(): Different from the way XHR Injection executes responseText, the responseText is directly placed in the eval() function for execution.

var createXHR  = function() {
    var obj;
    if(window.XMLHttpRequest)
        obj = new XMLHttpRequest();
    else
        obj = new ActiveObject("Microsoft.XMLHTTP");
    return obj;
};
var xhr = createXML();
xhr.open("GET", "http://cdn.bootcss.com/jquery/3.0.0-beta1/jquery.min.js", true);
xhr.send();
xhr.onreadystatechange = function() {
    if(xhr.readyState == 4 && xhr.status == 200) {
        eval(xhr.responseText);
        $(&#39;#btn&#39;).click(function() {
            alert($(this).text());
        });
    }
}

Script In Iframe: Insert an iframe element in the parent window, and then load JS in the iframe.

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

2. Lazy loading

        有些JS代码在某些情况下需要使用,并不是页面初始化的时候就要用到。延迟加载就是为解决这个问题。将JS切分成许多模块,页面初始化时只将事件处理程序添加到UI元素上,然后其它JavaScript代码的加载延迟到第一次用户交互或者其他条件需要用到的时候再加载。类似图片的懒加载。这样做的目的是可以渐进式地载入页面,尽可能快地为用户提供目前需要的信息,其余部分的内容可以在用户浏览该页面时在后台载入。

        JavaScript的加载分为两个部分:下载和执行脚本,异步加载只解决了下载的问题,但是代码在下载完成后就可能会立即执行,在执行过程中浏览器储与阻塞状态,响应不了任何需求。为了解决JavaScript延迟加载的问题,可以利用异步加载缓存起来,所以不会立即执行,然后在第一次需要的时候再执行。

        第二部分内容的载入可以用创建动态脚本的形式:

window.onload = function() {    
var script = document.createElement("script");
    script.type="text/javascript";
    script.src="demo.js";
    document.documentElement.firstChild.appendChild("script");
}

3. 按需加载

        可以通过创建一个require方法,包含需要加载的脚本名称和附加脚本加载完成后需要执行的回调函数。

function require(file, callback) {    
var script = document.getElementsByTagName("script")[0];   
var newjs = document.createElement("script");

    newjs.onload= function() {
        callback();
    };
    newjs.src=file;
    script.parentNode.insertBefore(newjs, script);
}

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

关于javascrip的立即执行函数的解析

深入理解JS正则表达式之REGEXP对象属性的解析

The above is the detailed content of Analysis of Javascript loading. 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
Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

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.

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment