Home Web Front-end JS Tutorial Key answers to dynamic loading of JS scripts, to the point

Key answers to dynamic loading of JS scripts, to the point

May 17, 2018 am 11:00 AM
javascript load Script

Use ajax to develop a website. When using ajax, you need to use a lot of JS code, and not all the code is used on the first loaded page.

So there are a lot of Dynamic loading of JS code is more suitable. Four methods are introduced below. In ajax development, the first method is not suitable. Methods 2, 3, and 4.

is essentially a method, detailed The method of dynamically loading JS is as follows:
1. Directlydocument.write

<scrīpt language="javascrīpt"> 
    document.write("<scrīpt src=&#39;test.js&#39;><//scrīpt>"); 
</scrīpt>
Copy after login

2. Dynamically change the src attribute of an existing scrīpt

<scrīpt src=&#39;&#39; id="s1"></scrīpt> 
<scrīpt language="javascrīpt"> 
    s1.src="test.js" 
</scrīpt>
Copy after login

3. Dynamically create a scrīpt Element

<scrīpt> 
    var oHead = document.
getElementsByTagName
(&#39;HEAD&#39;).item(0); 
    var oscrīpt= document.createElement("scrīpt"); 
    oscrīpt.type = "text/javascrīpt"; 
    oscrīpt.src="test.js"; 
    oHead.appendChild( oscrīpt); 
</scrīpt>
Copy after login

These three methods are all executed asynchronously, that is to say, while loading these scripts, the scripts on the main page continue to run. If the above method is used, the following code will not be obtained. expected effect.

JS script to be loaded dynamically: a.js, the following is the content of the file.

var str = "中国"; 
alert( "这是a.js中的变量:" + str );
Copy after login

Main page code:

<scrīpt language="Javascrīpt"> 
function LoadJS( id, fileUrl ) 
{ 
    var scrīptTag = document.getElementById( id ); 
    var oHead = document.getElementsByTagName(&#39;HEAD&#39;).item(0); 
    var oscrīpt= document.createElement("scrīpt"); 
    if ( scrīptTag  ) oHead.removeChild( scrīptTag  ); 
    oscrīpt.id = id; 
    oscrīpt.type = "text/javascrīpt"; 
    oscrīpt.src=fileUrl ; 
    oHead.appendChild( oscrīpt); 
} 
LoadJS( "a.js" ); 
alert( "主页面动态加载a.js并取其中的变量:" + str ); 
</scrīpt>
Copy after login

After the above code is executed, the alert of a.js is executed and a message pops up.

However, an error occurs on the main page and no dialog box pops up. The reason is that 'str' is undefined, why? Because a.js is not fully loaded successfully when the main page retrieves the

of str. When you need to execute a script synchronously, you can use the fourth method below.

4. Principle: Use XMLHTTP to obtain the content of the script, and then create a scrīpt object.
Note: a.js must be saved in UTF8 encoding to avoid errors. Because the server and XML use UTF8 encoding to transmit data.
Main page code:

<scrīpt language="Javascrīpt"> 
function GetHttpRequest() 
{ 
    if ( window.XMLHttpRequest ) // Gecko 
        
return
 new XMLHttpRequest() ; 
    else if ( window.ActiveX
Object
 ) // IE 
        return new ActiveXObject("MsXml2.XmlHttp") ; 
} 
function AjaxPage(sId, url){ 
    var oXmlHttp = GetHttpRequest() ; 
    oXmlHttp.OnReadyStateChange = function()  
    { 
        if ( oXmlHttp.readyState == 4 ) 
        {
            if ( oXmlHttp.status == 200 || oXmlHttp.status == 304 ) 
            {
                
Include
JS( sId, url, oXmlHttp.responseText );
            } 
            else 
            { 
                alert( &#39;XML request error: &#39; + oXmlHttp.statusText + &#39; (&#39; + oXmlHttp.status + &#39;)&#39; ) ; 
            } 
        } 
    } 
    oXmlHttp.open(&#39;GET&#39;, url, true); 
    oXmlHttp.send(null); 
} 
function IncludeJS(sId, fileUrl, source) 
{ 
    if ( ( source != null ) && ( !document.getElementById( sId ) ) ){ 
        var oHead = document.getElementsByTagName(&#39;HEAD&#39;).item(0); 
        var oscrīpt = document.createElement( "scrīpt" ); 
        oscrīpt.language = "javascrīpt"; 
        oscrīpt.type = "text/javascrīpt"; 
        oscrīpt.id = sId; 
        oscrīpt.defer = true; 
        oscrīpt.text = source; 
        oHead.appendChild( oscrīpt ); 
    } 
} 
AjaxPage( "scrA", "b.js" ); 
alert( "主页面动态加载JS脚本。"); 
alert( "主页面动态加载a.js并取其中的变量:" + str ); 
</scrīpt>
Copy after login

Use ajax to load JS code synchronously. It’s okay to load one, but when there are two, three or more, it’s faster to load asynchronously.

I use the third method. I name each JS. When a JS is loaded, a flag is set to indicate that it has been loaded.

//所有的JS文件   
var jsM = {   
    page         : false  ,   
    dhtmlXTree  : false ,   
    photo_tree  : false    
   };   
function getJSM(f)   
{   
    var reg = ///(/w+)/./;   
    jF = f.match(reg);   
    return jF[jF.length-1];   
}   
function loadJS(js)   
{   
 id = getJSM(js);   
 var scrīptId = document.getElementById(id);   
 var head = document.getElementsByTagName(&#39;head&#39;).item(0);   
 if(scrīptId)   
 {   
  //head.removeChild(id);   
 }   
 else  
 {   
  scrīpt  = document.createElement(&#39;scrīpt&#39;);   
  scrīpt.src = js;   
  scrīpt.type = &#39;text/javascrīpt&#39;;   
  scrīpt.id = id;   
  head.appendChild(scrīpt);   
 }   
}   
//JS时候,判断jsM中,代表其模块的标识是否为true,如果为false,则尚未加载   
loadJS("page.js")   
[js] view plain copy
//所有的JS文件  
var jsM = {  
page         : false  ,  
dhtmlXTree  : false ,  
photo_tree  : false  
};  
function getJSM(f)  
{  
var reg = ///(/w+)/./;  
jF = f.match(reg);  
return jF[jF.length-1];  
}  
function loadJS(js)  
{  
id = getJSM(js);  
var scrīptId = document.getElementById(id);  
var head = document.getElementsByTagName(&#39;head&#39;).item(0);  
if(scrīptId)  
{  
//head.removeChild(id);  
}  
else  
{  
scrīpt  = document.createElement(&#39;scrīpt&#39;);  
scrīpt.src = js;  
scrīpt.type = &#39;text/javascrīpt&#39;;  
scrīpt.id = id;  
head.appendChild(scrīpt);  
}  
}  
//JS时候,判断jsM中,代表其模块的标识是否为true,如果为false,则尚未加载  
loadJS("page.js")
Copy after login

The above is the dynamic loading JS script I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Traverse the values ​​in the EL expression List collection in javascript

How to use <script> The el expression can also be used in the </script> tag

An analysis and solution to the key points of rewriting and polymorphism

The above is the detailed content of Key answers to dynamic loading of JS scripts, to the point. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to create a script for editing? Tutorial on how to create a script through editing How to create a script for editing? Tutorial on how to create a script through editing Mar 13, 2024 pm 12:46 PM

Cutting is a video editing tool with comprehensive editing functions, support for variable speed, various filters and beauty effects, and rich music library resources. In this software, you can edit videos directly or create editing scripts, but how to do it? In this tutorial, the editor will introduce the method of editing and making scripts. Production method: 1. Click to open the editing software on your computer, then find the "Creation Script" option and click to open. 2. In the creation script page, enter the "script title", and then enter a brief introduction to the shooting content in the outline. 3. How can I see the "Storyboard Description" option in the outline?

How to execute .sh file in Linux system? How to execute .sh file in Linux system? Mar 14, 2024 pm 06:42 PM

How to execute .sh file in Linux system? In Linux systems, a .sh file is a file called a Shell script, which is used to execute a series of commands. Executing .sh files is a very common operation. This article will introduce how to execute .sh files in Linux systems and provide specific code examples. Method 1: Use an absolute path to execute a .sh file. To execute a .sh file in a Linux system, you can use an absolute path to specify the location of the file. The following are the specific steps: Open the terminal

Error loading plugin in Illustrator [Fixed] Error loading plugin in Illustrator [Fixed] Feb 19, 2024 pm 12:00 PM

When launching Adobe Illustrator, does a message about an error loading the plug-in pop up? Some Illustrator users have encountered this error when opening the application. The message is followed by a list of problematic plugins. This error message indicates that there is a problem with the installed plug-in, but it may also be caused by other reasons such as a damaged Visual C++ DLL file or a damaged preference file. If you encounter this error, we will guide you in this article to fix the problem, so continue reading below. Error loading plug-in in Illustrator If you receive an "Error loading plug-in" error message when trying to launch Adobe Illustrator, you can use the following: As an administrator

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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.

Stremio subtitles not working; error loading subtitles Stremio subtitles not working; error loading subtitles Feb 24, 2024 am 09:50 AM

Subtitles not working on Stremio on your Windows PC? Some Stremio users reported that subtitles were not displayed in the videos. Many users reported encountering an error message that said "Error loading subtitles." Here is the full error message that appears with this error: An error occurred while loading subtitles Failed to load subtitles: This could be a problem with the plugin you are using or your network. As the error message says, it could be your internet connection that is causing the error. So please check your network connection and make sure your internet is working properly. Apart from this, there could be other reasons behind this error, including conflicting subtitles add-on, unsupported subtitles for specific video content, and outdated Stremio app. like

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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 JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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

Windows PowerShell Scripting Tutorial for Beginners Windows PowerShell Scripting Tutorial for Beginners Mar 13, 2024 pm 10:55 PM

We've designed this Windows PowerShell scripting tutorial for beginners, whether you're a tech enthusiast or a professional looking to improve your scripting skills. If you have no prior knowledge of PowerShell scripting, this article will start with the basics and be tailored for you. We'll help you master the installation steps for a PowerShell environment and walk you through the main concepts and features of PowerShell scripts. If you're ready to learn more about PowerShell scripting, let's embark on this exciting learning journey together! What is WindowsPowerShell? PowerShell is a hybrid command system developed by Microsoft

See all articles