The dynamic scripting element is in JS to create <script> tag to load external JS and execute, so the advantage of loading is that the file download and execution process will not block the page of other processes. Compare the results with the following two examples
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "><script src= "1.js" type= "Text/javascript" ></script><script type= "Text/javascript" > window.onload = function () { var i = 0; while (I < 1000000000) { i++; } Alert ("Internal JS"); } </script>A.html
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">loadscript ("1.js", function () {alert ("Load external JS complete")})var i = 0; while (I < 1000000000) {i++; } alert ("Internal JS"); }function Loadscript (url,callback) {var script=document.createelement ("script"); script.type= "Text/javascript"; if ( Script.readystate) {script.onreadystatechange=function () {if (script.readystate== "Loaded" | | script.readystate== " Complete ") {Script.onreadystatechange=null;callback ();}};} Else{script.onload=function () {callback ();};} Script.src=url;document.getelementsbytagname ("Head") [0].appendchild (script);} </script>B.html
var i = 0;while (i < 1000000000) { i++;} Alert ("External JS");
1.js
After the execution, it will be found that the a.html execution result is alert ("External JS") alert ("Internal JS") render Tree rendering
B.html execution results for alert ("Internal JS") Render Tree Rendering alert ("External JS") alert ("Load external js complete")
By comparing the results, it is more intuitive to understand the other processes without blocking the page
In addition to the dynamic loading JS, there are XMLHttpRequest object get script is also non-blocking, the sample code is as follows
var xhr=new xmlhttprequest (); Xhr.open ("Get", "1.js", true); Xhr.onreadystatechange=function () { if ( xhr.readystate==4) { if (xhr.status >= && xhr.status<300 | | xhr.status = 304) { var script =document.createelement ("script"); Script.type= "Text/javascript"; Script.text=xhr.responsetext; Document.body.appendChild (script); }}} Xhr.send (NULL);
Dynamic scripting elements