html加载js文件失败,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語句
function ReloadScript(c_id) {
document.getElementById('script').src = 'a.js?_dc=' + new Date().getTime(); //加時間戳也無用
alert(document.getElementById('script').src)//firefox,chrome雖然script的src變了,但是并沒有加載js文件
}
test.html,script未加載js文件,第一次加載能執行alert,第二次就不行了
function ReloadScript(c_id) {
document.getElementById('script').src = 'a.js?_dc=' + new Date().getTime(); //加時間戳也無用
alert(document.getElementById('script').src)//firefox,chrome雖然script的src變了,但是并沒有加載js文件
}
解決方法,使用DOM方法創建script并添加到head節點中
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);
}
加支付寶好友偷能量挖...
2012-11-15Web開發網
閱讀(743)喜歡(0)
總結
以上是生活随笔為你收集整理的html加载js文件失败,firefox/chrome动态设置script加载js文件失败的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 云表中表单配置内嵌浏览器
- 下一篇: Intellij IDEA快捷键大全(超