


Detailed explanation of Javascript loading and execution_Basic knowledge
First of all, I want to talk about the loading and execution of Javascript. Generally speaking, browsers have two major characteristics for running Javascript: 1) it is executed immediately after loading, 2) when executed, it will block the subsequent content of the page (including the rendering of the page and the downloading of other resources). Therefore, if multiple js files are introduced, then for the browser, these js files are loaded serially and executed in sequence.
Because javascript may operate the DOM tree of the HTML document, browsers generally do not download js files in parallel with downloading css files in parallel, because this is caused by the particularity of js files. Therefore, if your javascript wants to operate the subsequent DOM elements, basically the browser will report an error saying that the object cannot be found. Because when Javascript is executed, the subsequent HTML is blocked, and there is no subsequent DOM node in the DOM tree. So the program reported an error.
The traditional way
So, when you write in code write the following code:
Basically speaking, the <script> tag in the head will block the loading of subsequent resources and the generation of the entire page. I made a special example for you to take a look at: Example 1. Note: There is only one sentence in my alert.js: alert("hello world"), which makes it easier for you to see how javascript blocks the following things. </p>
<p>So, you know why many websites put javascript at the end of the web page, or use events such as window.onload or docmuemt ready. </p>
<p>In addition, because most Javascript codes do not need to wait for the page, we have asynchronous loading function. So how do we load asynchronously? </p>
<p>document.write method</p>
<p>So, you may think that document.write() can solve the problem without blocking. Of course you would think that after document.write the <script> tag, you can execute the following things, which is correct. This is true for Javascript code in the same script tag, but for the entire page, this will still block. The following is a test code: </p>
<p></p>
<div class="codetitle">
<span><a style="CURSOR: pointer" data="35700" class="copybut" id="copybut35700" onclick="doCopy('code35700')"><u>Copy code</u></a></span> The code is as follows:</div>
<div class="codebody" id="code35700">
<br>
<script type="text/javascript" language="javascript"><br>
Function loadjs(script_filename) {<br>
document.write('<' 'script language="javascript" type="text/javascript"');<br />
document.write(' src="' script_filename '">');<br>
document.write('<' '/script' '>');<br>
alert("loadjs() exit...");<br>
}<br>
var script = 'http://coolshell.cn/asyncjs/alert.js';<br>
Loadjs(script);<br>
alert("loadjs() finished!");<br>
</script>
What do you think is the order of alerts? You can try it in different browsers. Here is the test page you want to close: Example 2.
script’s defer and async attributes
IE has supported defer tags since IE6, such as:
For IE, this tag will cause IE to download the js file in parallel and hold its execution until the entire DOM is loaded (DOMContentLoaded). Multiple defer <script> will also be executed in the order in which they appear. to run. The most important thing is that after <script> is added to defer, it will not block subsequent DOM rendering. But because this defer is only for IE, it is generally used less. </p>
<p>Our standard HTML5 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 js files asynchronously. However, asynchronous loading of async has a serious problem, that is, it faithfully implements the military rule of "execute immediately after loading". Therefore, although it does not block the rendering of the page, you cannot control it. The order and timing of his execution. You can take a look at this example to get a feel for it. </p>
<p>Browsers that support async tags are: Firefox 3.6, Chrome 8.0, Safari 5.0, IE 10, Opera does not support it yet (from here), so this method is not very good. Because not all browsers can do it. </p>
<p>Dynamic creation of DOM</p>
<p>This method is probably the most commonly used. </p>
<p></p>
<div class="codetitle">
<span><a style="CURSOR: pointer" data="53194" class="copybut" id="copybut53194" onclick="doCopy('code53194')"><u>Copy code</u></a></span> The code is as follows:</div>
<div class="codebody" id="code53194">
<br>
function loadjs(script_filename) {<br>
var script = document.createElement('script');<br>
script.setAttribute('type', 'text/javascript');<br>
script.setAttribute('src', script_filename);<br>
script.setAttribute('id', 'coolshell_script_id');<br>
<br>
script_id = document.getElementById('coolshell_script_id');<br>
If(script_id){<br>
document.getElementsByTagName('head')[0].removeChild(script_id);<br>
}<br>
Document.getElementsByTagName('head')[0].appendChild(script);<br>
}<br>
<br>
var script = 'http://coolshell.cn/asyncjs/alert.js';<br>
loadjs(script);<br>
</div>
<p>This method has almost become the standard way to load js files asynchronously. For a demonstration of this method, please see: Example 3. This method has also been exploited by JSONP, that is, I 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, and returns Call our predefined javascript function. You can take a look at this example: t.js (This example is a small example of asynchronous ajax call that I solicited on Weibo before) </p>
<p>Load js asynchronously on demand</p>
<p>The above example of DOM method solves the problem of asynchronous loading of Javascript, but it does not solve the problem of us wanting it to run at the timing we specify. Therefore, we only need to tie the above DOM method to a certain event. </p>
<p>For example: </p>
<p>Tie to window.load event - Example 4</p>
<p>You must compare the execution differences between Example 4 and Example 3. I specifically used a code highlighting javascript in both examples to see the execution and execution of the code highlighting script. You will know the difference based on the execution of my alert.js) </p>
<p></p>
<div class="codetitle">
<span><a style="CURSOR: pointer" data="34632" class="copybut" id="copybut34632" onclick="doCopy('code34632')"><u>Copy code</u></a></span> The code is as follows:</div>
<div class="codebody" id="code34632">
<br>
window.load = loadjs("<a href="http://coolshell.cn/asyncjs/alert.js">http://coolshell.cn/asyncjs/alert.js</a>")<br>
</div>
<p>Tie to a specific event - Example 5</p>
<p></p>
<div class="codetitle">
<span><a style="CURSOR: pointer" data="16878" class="copybut" id="copybut16878" onclick="doCopy('code16878')"><u>Copy code</u></a></span> The code is as follows:</div>
<div class="codebody" id="code16878">
<br>
<p style="cursor: pointer" onclick="LoadJS()">Click to load alert.js </p><br>
</div>
<p>This example is very simple. When you click on a DOM element, our alert.js will actually be loaded. </p>
<p>More</p>
<p>However, binding to a specific event seems to be a bit too much, because the js will only be actually downloaded when clicked, which would be too slow. Okay, here we come to our ultimate question - we want to asynchronously download the js file to the user's local area, but not execute it, only execute it when we want to execute it. </p>
<p>It would be great if we had something like this: </p>
<p></p>
<div class="codetitle">
<span><a style="CURSOR: pointer" data="43581" class="copybut" id="copybut43581" onclick="doCopy('code43581')"><u>Copy code</u></a></span> The code is as follows:</div>
<div class="codebody" id="code43581">
<br>
var script = document.createElement("script");<br>
script.noexecute = true;<br>
script.src = "alert.js";<br>
document.body.appendChild(스크립트);<br>
<br>
//나중에 할 수 있습니다<br>
script.execute();<br>
</div>
<p>안타깝게도 이것은 단지 아름다운 꿈일 뿐입니다. 오늘날 우리의 Javascript는 여전히 상대적으로 원시적이며 이 "JS 꿈"은 아직 실현되지 않았습니다. </p>
<p>따라서 우리 프로그래머는 해킹 방법만을 사용하여 이를 수행할 수 있습니다. </p>
<p>일부 프로그래머는 비표준 스크립트 유형을 사용하여 자바스크립트를 캐시합니다. 예: </p>
<p></p>
<div class="codetitle">
<span><a style="CURSOR: pointer" data="63471" class="copybut" id="copybut63471" onclick="doCopy('code63471')"><u>코드 복사</u></a></span> 코드는 다음과 같습니다.</div>
<div class="codebody" id="code63471">
<br>
<스크립트 유형=cache/script src="./alert.js"></script>
이런 건 "캐시/스크립트" 때문에 브라우저에서 전혀 파싱할 수 없어서 브라우저에서 자바스크립트로 Alert.js를 실행할 수 없지만, js 파일을 다운로드 받아야 해결이 가능합니다. 웹킷이 HTML 표준을 엄격하게 준수한다는 것은 유감스러운 일입니다. 인식하지 못하는 내용은 삭제하고 아무것도 하지 마십시오. 그래서 우리의 꿈은 또 산산조각이 났습니다.
그러므로 다시 해킹해야 합니다. 수년 전에 사전 로드된 이미지를 가지고 놀았던 것처럼 객체 태그(또는 iframe 태그)를 사용할 수 있으므로 다음 코드가 있습니다.
함수 캐시js(script_filename){
var 캐시 = document.createElement('객체');
캐시.데이터 = script_filename;
캐시.id = "coolshell_script_cache_id";
캐시.폭 = 0;
캐시.높이 = 0;
Document.body.appendChild(캐시);
}
그런 다음 마지막에 이 함수를 호출합니다. 관련 예시를 살펴보세요: 예시 6
Chrome에서 Ctrl Shit I을 누르고 네트워크 페이지로 전환하면 Alert.js가 다운로드되었지만 실행되지 않은 것을 볼 수 있습니다. 그러면 브라우저 측에 캐시가 있으므로 예제 5의 방법을 사용하겠습니다. 다시 실행되지 않습니다. 서버에서 Alert.js를 다운로드하세요. 따라서 실행 속도를 보장할 수 있습니다.
이런 종류의 사전 로드에 대해 잘 알고 있어야 합니다. 다음과 같은 Ajax를 사용할 수도 있습니다.
var xhr = 새로운 XMLHttpRequest();
xhr.open('GET', 'new.js');
xhr.send('');
여기서 더 이상 말하거나 예를 제시하지 않겠습니다. 직접 시도해 보세요.
마지막으로 두 개의 js에 대해 언급하겠습니다. 하나는 ControlJS이고 다른 하나는 HeadJS입니다. 이는 자바스크립트 파일을 비동기적으로 로드하는 데 특별히 사용됩니다.
자, 이상이 내용입니다. 이 내용을 읽으신 후 Javascript 로딩 및 실행은 물론 관련 기술에 대한 이해를 가지실 수 있기를 바랍니다. 동시에 모든 프론트엔드 전문가들이 여러분에게 조언을 해주길 바랍니다!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

CIFS, also known as Common Internet File System, is a variant of SMB (Server Message Block) designed to provide shared access to folders, files, and printers over a small local area network (LAN). Linux comes with the CIFS-Utils package for mounting and managing cross-platform files and printers over a local network using the CIFS protocol. mount.cifs is part of the LinuxCIFS-Utils package. In this tutorial, I will explore how to mount a shared folder on Linux using the Linuxmount.cifs utility. Note that the CIFS protocol has been replaced by the SMB2 and SMB3 protocols, which are more secure. In Windows system

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to write PHP code in the browser and keep the code from being executed? With the popularization of the Internet, more and more people have begun to come into contact with web development, and learning PHP has also attracted more and more attention. PHP is a scripting language that runs on the server side and is often used to write dynamic web pages. However, during the exercise phase, we want to be able to write PHP code in the browser and see the results, but we don't want the code to be executed. So, how to write PHP code in the browser and keep it from being executed? This will be described in detail below. first,
