这次给大家带来如何动态引入js文件,动态引入js文件的注意事项有哪些,下面就是实战案例,一起来看一下。
index.html
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="content-type">
<title> </title>
<script src='' id="s1"></script>
<script src="dynamic.js"></script>
</head>
<body>
</body>
</html>
test.js
alert(hello! i am test.js);
var str=1;
dynamic.js
//第一种方式:直接document.write 但这样会把当前的页面全覆写掉
//document.write(<script src='test.js'><\/script>);
//第二种方式:动态改变已有script的src属性
//s1.src=test.js
//第三种方式:动态创建script元素
/* var ohead = document.getelementsbytagname('head').item(0);
var oscript= document.createelement(script);
oscript.type = text/javascript;
oscript.src=test.js;
ohead.appendchild(oscript);
*/
//其实原理就是利用dom动态的引入一个js到文件中来~就能和原有的js通信了~
//alert(str);
/*以上三种方式都采用异步加载机制,也就是加载过程中,页面会往下走,
如果这样的话会有问题的,如上面的str就访问不到,因为当程序执行alert(str)时,test.js还在加载ing....
那么第四种就是基于ajax请求的,且是推荐
*/
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)
{
includejs( sid, url, oxmlhttp.responsetext );
}
}
oxmlhttp.open('get', url, false);//同步操作
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.type = text/javascript;
oscript.id = sid;
oscript.text = source;
ohead.appendchild( oscript );
}
}
ajaxpage( scra, test.js );
alert( 主页面动态加载js脚本。);
alert( 主页面动态加载a.js并取其中的变量: + str );
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
js生成范围随机与序列随机步骤详解
es6的class特性使用案例详解
在js中如何使用call、apply
以上就是如何动态引入js文件的详细内容。