//option= {type,src,text,isCreateScriptBySrc} function createDynamicScript(option){ var script = document.createElement("script"); script.type = "text/javascript"; // console.log("option.isCreateScriptBySrc:", option.isCreateScriptBySrc); try{ if((option.isCreateScriptBySrc == undefined) || (!!(option.isCreateScriptBySrc) == true)){ script.src = option.src; } else { script.text = option.text; } document.body.appendChild(script); }catch(error){ console.error("#dynamicScript: load script failed!"); } }
demo:
var option = { "type":"text/javascript", "src":"https://ss0.bdstatic.com/-0U0bnSm1A5BphGlnYG/tam-ogel/5d4e9b24-dcc5-483a-b6da-be1e9e621891.js", "text":"function log(){ console.log("created log()"); }; log();", "isCreateScriptBySrc":true//优先选择src作为创建脚本的数据来源 } //execute createDynamicScript(option); option.isCreateScriptBySrc = false; createDynamicScript(option);
小结:
创建JavaScript动态脚本的方式有两种:
1.通过src引入外部脚本
2.通过JavaScript元素本身内置代码