In daily front-end development, occasionally there is a need to dynamically insert JavaScript code. The basic idea is:
1. Dynamically create a script tag and set its src attribute, type attribute, etc.
2 , insert the script node into the page and load the js file
which is equivalent to adding to the page, except This process is completed dynamically, and a function is specially encapsulated for this purpose:
// Dynamically insert script tags
function createScript(url, callback){
var oScript = document.createElement('script');
oScript.type = 'text/javascript';
oScript.async = true;
oScript.src = url;
/*
** onload and onreadystatechange events of script tag
** IE6/7/8 supports onreadystatechange event
** IE9/10 supports onreadystatechange and onload events
** Firefox/Chrome/Opera supports onload events
*/
// Determine IE8 and below browsers
var isIE = ! -[1,];
if(isIE){
alert('IE')
oScript.onreadystatechange = function(){
if(this.readyState == 'loaded' || this .readyState == 'complete'){
callback();
}
}
} else {
// IE9 and above browsers, Firefox, Chrome, Opera
oScript .onload = function(){
callback();
}
}
document.body.appendChild(oScript);
}
Used as follows :
createScript('xxx.js', function() {
console.log('OK');
});