Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to load JavaScript files dynamically

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article Xiaobian for you to introduce in detail "how to dynamically load JavaScript file", the content is detailed, the steps are clear, the details are handled properly, I hope this "how to dynamically load JavaScript file" article can help you solve your doubts, following the editor's ideas slowly in-depth, let's learn new knowledge together.

Dynamic loading of JavaScript files is one of the very useful tools you must have. It allows you to optimize web page performance by removing blocking scripts from the loading process (often referred to as "deferred loading") and loading scripts only when users need them (often referred to as "on-demand loading"). If you use this tool wisely, it will greatly improve your page performance.

Configuration

Let's define our example model, starting with defining remote files that need to be loaded dynamically. This is the definition of the "remote.js" file:

/ / this is going to be executed when script is loaded (function () {console.log ("Remote script loaded");} ()); var sayHello = function (name) {alert ("Hello", name);}

In the above code, we define an immediate function to track file loading. We also define a custom function that is called from the main page.

Now, this is our main "index.htm" page. It contains only one button for loading and testing files.

Load script file document.getElementById ('loadButton'). Onclick = function () {/ / your code goes here}

The most straightforward way to load an JavaScript file is to reference it in an element. The easiest way to dynamically load this file is to load this element dynamically! Can't you see that it is coming? Really? )

Let's update the code and see the actual results:

Document.getElementById ("loadButton"). Onclick = function () {var script = document.createElement ("script"); script.src = "remote.js"; script.onload = function () {sayHello ("Mohammad");}; / / append and execute script document.documentElement.firstChild.appendChild (script);}

The above code simply creates an element and sets the field of the element src to the path of our file. It then uses the appendChild () function to attach it to the first child element of our code.

Now, let's ReFactor the above code and modify it slightly so that it can be used anywhere else:

/ * Used to load and execute javascript file. An be used cross-domain seamlessly. * @ param file JS file name * @ param callback Subscribe to get notified when script file is loaded * * / function require (file, callback) {/ / create script element var script = document.createElement ("script"); script.src = file / / monitor script loading / / IE < 7, does not support onload if (callback) {script.onreadystatechange = function () {if (script.readyState = "loaded" | | script.readyState = "complete") {/ / no need to be notified again script.onreadystatechange = null; / / notify user callback ();}; / / other browsers script.onload = function () {callback ();} } / / append and execute script document.documentElement.firstChild.appendChild (script);} document.getElementById ("loadButton"). Onclick = function () {require ("remote.js", function () {sayHello ("Mohammad");});}

Now you can easily call the require () JavaScript path and callback function to be notified when the script is loaded.

Laborious method

Another way to load a JavaScript file dynamically is to retrieve it using a classic HTTP request. This is a pure JavaScript call, but it has many disadvantages. Let's see how it actually works:

/ * Used to load and execute javascript file. Suffers from same-domain restriction. * @ param file JS file name * @ param callback Subscribe to get notified when script file is loaded * * / function requireXhr (file, callback) {/ / object initialization const xhr = new XMLHttpRequest (); / / subscribe to request events xhr.onreadystatechange = function () {/ / readyState: / / 0 UNSENT Client has been created. Open () not called yet. / / 1 OPENED open () has been called. / / 2 HEADERS_RECEIVED send () has been called, and headers and status are available. / / 3 LOADING Downloading; responseText holds partial data. / / 4 DONE The operation is complete. / / when not done, return if (xhr.readyState! = = 4) {return;} / / done, check status code if (xhr.status! = = 200) / / 200 = OK {return;} / / now the file is loaded, / / go and execute the script eval (xhr.responseText); / / notify caller if (callback) {callback ();}} / / open connection to file xhr.open ("GET", file, true); / / send the request xhr.send ();} document.getElementById ("loadButton"). Onclick = function () {requireXhr ("remote.js", function () {sayHello ("Mohammad");});}

The code is very simple and self-descriptive. We use XMLHttpRequestobject to set up a HTML request and then trigger it. Then, we monitor the state change and execute it accordingly.

When we execute the above code, we get the following results. We can see our successful XHR request in the DevTools extension

On the other hand, the results are disappointing. We can run the script successfully, and there are no clues to the script file in the HTML content, but because of the private scope of eval (), we cannot call the loaded function.

Simple method

Now is the most direct way to delay loading JavaScript files, the jQuery way. JQuery provides a function called getScript () (which is short for ajax ()) to retrieve and load JavaScript files. This is the code:

/ * Used to load and execute JavaScript file. * @ param file JS file name * @ param callback Subscribe to get notified when script file is loaded * * / function requireAjax (file, callback) {jQuery.getScript (file, callback);} document.getElementById ("loadButton"). Onclick = function () {requireAjax ("remote.js", function () {sayHello ("Mohammad");});}

Although XMLHttpRequest is used in the internal jQuery.getScript (), and you can see the request in the XHR list in DevTools, it does not suffer from the XMLHttpRequest. It is easier to use and execute XMLHttpRequest than raw.

Read here, this "how to dynamically load JavaScript file" article has been introduced, want to master the knowledge of this article also need to practice and use to understand, if you want to know more about the article, welcome to pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report