我正在將<script>
標記動態添加到頁面的<head>
,並且我想知道加載是否以某種方式失敗-404,加載的腳本中的腳本錯誤等。
在Firefox中,這有效:
var script_tag = document.createElement('script');
script_tag.setAttribute('type', 'text/javascript');
script_tag.setAttribute('src', 'http://fail.org/nonexistant.js');
script_tag.onerror = function() { alert("Loading failed!"); }
document.getElementsByTagName('head')[0].appendChild(script_tag);
但是,這在IE或Safari中不起作用。
有誰知道在Firefox以外的瀏覽器中實現此目的的方法嗎?
(我認為不需要在.js文件中放置特殊代碼的解決方案是一個很好的解決方案。它既笨拙又不靈活。)