Home  >  Article  >  Web Front-end  >  4 ways to dynamically load scripts in JS_javascript skills

4 ways to dynamically load scripts in JS_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:53:251149browse

If the js files are relatively small, it is better to use one js file, which can reduce the number of connections. The following are 4 commonly used methods. You can choose according to the situation. Finally, Script House will recommend one.
1. Direct document.write

Copy code The code is as follows:

");


2. Dynamically change the src attribute of an existing script
Copy code The code is as follows:




3. Dynamically create script elements
Copy the code The code is as follows:

<script> <br>var oHead = document.getElementsByTagName('HEAD').item(0); <br> var oScript= document.createElement("script"); <br>oScript.type = "text/javascript"; <br>oScript.src="test.js"; <br>oHead.appendChild( oScript); <br></script>

These three methods are all executed asynchronously, that is to say, while loading these scripts, the script on the main page continues to run. If you use the above method, the following code will not have the expected effect.
JS script to be loaded dynamically: a.js, the following is the content of the file
Copy code Code As follows:

var str = "China";
alert( "This is a variable in a.js: " str );

Main page code:
Copy code The code is as follows:



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 fetching str on the main page. When you need to execute a script synchronously, you can use the fourth method below.
4. Principle: Use XMLHTTP to obtain the content to be scripted, and then create a Script 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:
Copy code The code is as follows:

<스크립트 언어="JavaScript">
function GetHttpRequest()
{
if ( window.XMLHttpRequest ) // Gecko
return new XMLHttpRequest() ;
else if ( window.ActiveXObject ) // 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 )
{
IncludeJS( sId, url, oXmlHttp.responseText );
}
else
{
alert( 'XML 요청 오류: ' oXmlHttp.statusText ' (' oXmlHttp.status ')' ) ;
}
}
}
oXmlHttp.open('GET', url, true);
oXmlHttp.send(null);
}
function includeJS(sId, fileUrl, source)
{
if ( ( source != null ) && ( !document.getElementById( sId ) ) ){
var oHead = document .getElementsByTagName('HEAD').item(0);
var oScript = document.createElement( "script" );
oScript.언어 = "자바스크립트";
oScript.type = "텍스트/자바스크립트";
oScript.id = sId;
oScript.defer = true;
oScript.text = 소스;
oHead.appendChild(oScript);
}
}
AjaxPage( "scrA", "b.js" );
alert("主页면动态加载JS脚本。");

现在完成了一个JS脚本的动态加载。

复代代码 代码如下:
var Rash=true;
var msg="";
function norash()
{
if (confirm("确定要取消吗"))
Rash=false;
}
함수라시트()
{
setInterval('getrss()',Inttime);
}
function getrss()
{
if (Rash==true)
{
head=document.getElementsByTagName('head').item(0);
script=document.createElement('스크립트');
script.src='INCLUDE/AutoUpdate.asp';
script.type='text/javascript';
script.defer=true;
void(head.appendChild(스크립트));
window.status=msg;
}
}
rashit();

注意文字加粗的地方,大家可以情况选择。
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