I. document.write ()
<!DOCTYPE HTML>
<HTMLLang= "en">
<Head>
<MetaCharSet= "UTF-8">
<title>Dynamic Load JS</title>
<Script>
functionInit () {
document.write (' <script src= ' dynamic.js ' ><\/script> ');
document.write (' <input type= ' button "onclick=" Load (); "value=" Load Complete "\/>");
}
Dynamicjs ();//error here, because the Dynamic.js file has not been loaded complete
functionLoad () {
Dynamicjs ();
}
</Script>
</Head>
<Body>
<inputtype= "button"onclick= "init ();"value= "Initialize Load" />
<!--<input type= "button" onclick= "Load ();" value= "Load Complete" > -
</Body>
</HTML>View Code
Problem, 1,document.write will rewrite the page, after clicking the Initialize Load button, the page redraw causes the original content to be lost, the commented out "Load complete" button in the above code is lost, so you need to create a button in the INIT function using the Document.Write method.
Problem 2, asynchronous loading, the direct call to the Dynamicjs method will error, because the JS file is not loaded, and after the code has started to run.
In conclusion, this method is not recommended.
Two. Dynamically changing the SRC attribute of an existing script
<!DOCTYPE HTML>
<HTMLLang= "en">
<Head>
<MetaCharSet= "UTF-8">
<title>Dynamic Load JS</title>
<ScriptID= "ABC"src=""></Script>
<Script>
functionInit () {
ABC.SRC = "Dynamic.js";
Dynamicjs ();//the error is called here because it is not loaded yet
}
functionLoad () {
Dynamicjs ();
}
</Script>
</Head>
<Body>
<inputtype= "button"onclick= "init ();"value= "Initialize Load" />
<inputtype= "button"onclick= "load ();"value= "Loaded Complete">
</Body>
</HTML>View Code
This code runs a problem, click "Load Complete" button or "uncaught REFERENCEERROR:DYNAMICJS is not defined"
Problem: Asynchronous Load issue
Three. Dynamically create a SCRIPT element
<!DOCTYPE HTML>
<HTMLLang= "en">
<Head>
<MetaCharSet= "UTF-8">
<title>Dynamic Load JS</title>
<Script>
functionInit () {
varMyScript = document.createelement (' script ');
MYSCRIPT.SRC = ' dynamic.js ';
Document.body.appendChild (MyScript);
Dynamicjs ();//the error is called here because it is not loaded yet
}
functionLoad () {
Dynamicjs ();
}
</Script>
</Head>
<Body>
<inputtype= "button"onclick= "init ();"value= "Initialize Load" />
<inputtype= "button"onclick= "load ();"value= "Loaded Complete">
</Body>
</HTML>View Code
Problem: There is no need to add the script element at the beginning of the page in relation to the second way, but there is also an asynchronous load problem.
Dynamically Loading JS scripts