firefox/chrome动态设置script加载js文件失败
firefox,chrome等w3c浏览器下面,设置script标签的src来动态加载js文件时,有2中情况
1)如果script标签已经加载过js文件,那么重新设置为其他js文件的路径时,无法加载这个js文件。
2)如果未加载过js文件,是一个空的script标签,那么第一次设置src时可以加载这个js文件,第二次设置就没用办法加载指定的js文件了。
即使增加时间戳也不行,但是在IE浏览器下不会出现这个问题。
测试代码如下
a.js
alert(123);
test.html,script加载过js文件,那么再次设置此script标签时无法加载js文件执行alert语句
<script type="text/javascript" id="script" src="a.js"></script> <script language="javascript"> function ReloadScript(c_id) { document.getElementById('script').src = 'a.js?_dc=' + new Date().getTime(); //加时间戳也无用 alert(document.getElementById('script').src)//firefox,chrome虽然script的src变了,但是并没有加载js文件 } </script> <input type="button" value="重新加载a.js" onclick="ReloadScript()"/>
test.html,script未加载js文件,第一次加载能执行alert,第二次就不行了
<script type="text/javascript" id="script" ></script> <script language="javascript"> function ReloadScript(c_id) { document.getElementById('script').src = 'a.js?_dc=' + new Date().getTime(); //加时间戳也无用 alert(document.getElementById('script').src)//firefox,chrome虽然script的src变了,但是并没有加载js文件 } </script> <input type="button" value="重新加载a.js" onclick="ReloadScript()"/>
解决方法,使用DOM方法创建script并添加到head节点中
<script language="javascript"> function ReloadScript(c_id) { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'a.js?_dc=' + new Date().getTime(); document.getElementsByTagName('head')[0].appendChild(script); } </script> <input type="button" value="重新加载a.js" onclick="ReloadScript()"/>
加支付宝好友偷能量挖...
原创文章,转载请注明出处:firefox/chrome动态设置script加载js文件失败