


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. </script>
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.
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?
document.write method
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: </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. </script>
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.
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.
Dynamic creation of DOM
This method is probably the most commonly used.
function loadjs(script_filename) {
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', script_filename);
script.setAttribute('id', 'coolshell_script_id');
script_id = document.getElementById('coolshell_script_id');
If(script_id){
document.getElementsByTagName('head')[0].removeChild(script_id);
}
Document.getElementsByTagName('head')[0].appendChild(script);
}
var script = 'http://coolshell.cn/asyncjs/alert.js';
loadjs(script);
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)
Load js asynchronously on demand
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.
For example:
Tie to window.load event - Example 4
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)
Tie to a specific event - Example 5
Click to load alert.js
This example is very simple. When you click on a DOM element, our alert.js will actually be loaded.
More
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.
It would be great if we had something like this:
var script = document.createElement("script");
script.noexecute = true;
script.src = "alert.js";
document.body.appendChild(스크립트);
//나중에 할 수 있습니다
script.execute();
안타깝게도 이것은 단지 아름다운 꿈일 뿐입니다. 오늘날 우리의 Javascript는 여전히 상대적으로 원시적이며 이 "JS 꿈"은 아직 실현되지 않았습니다.
따라서 우리 프로그래머는 해킹 방법만을 사용하여 이를 수행할 수 있습니다.
일부 프로그래머는 비표준 스크립트 유형을 사용하여 자바스크립트를 캐시합니다. 예:
이런 건 "캐시/스크립트" 때문에 브라우저에서 전혀 파싱할 수 없어서 브라우저에서 자바스크립트로 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 로딩 및 실행은 물론 관련 기술에 대한 이해를 가지실 수 있기를 바랍니다. 동시에 모든 프론트엔드 전문가들이 여러분에게 조언을 해주길 바랍니다!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

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.

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
