2012-09-26 25 views
1

我想從另一個服務器加載一個java腳本文件到我的網頁使用java腳本代碼document.write方法。像,如何在jQuery服務器上找到文件?

document.write("<script type='text/javascript' src='http://www.mydomain.com/js/myscript.js'></script>"); 

但各自的路徑不具有myscript.js所以其在瀏覽器錯誤控制檯扔404 File not found error

我該如何預測和避免這種錯誤?

如果可能預測錯誤,我將顯示替代消息而不是調用錯過的js文件函數。

+0

如果你的腳本創建某種目的或全局變量 - 檢查在你加載腳本的頁面。例如,如果myscript.js將「g」定義爲全局變量,請選中「if(g == undefined)throw some error」 –

回答

2

使用JavaScript加載腳本:

function onReadyState() { 
    console.error("Unable to load file: "+ this.src + ". Please check the file name and parh."); 
    return false; 
} 

function addJS(path){ 
    var e = document.createElement("script"); 
    e.onerror = onReadyState; 
    e.src = path; 
    e.type = "text/javascript"; 
    document.getElementsByTagName('head')[0].appendChild(e); 
} 

addJS('http://www.mydomain.com/js/myscript.js'); 
+0

謝謝,我測試了示例[here](http://jsbin.com/ovexip/1/編輯) – sureshunivers

0

如果請求的文件是在您的域(因爲它來自這個問題似乎是)只是做了以前的ajax調用(與HEAD方法)的資源,並檢查是否響應狀態是200(OK)或304(未修改)

0

嘗試這種方法

var js="ajax/test.js"; 

    $.getScript(js) .done(function(script, textStatus) { 
      var script = document.createElement('script'); 
      script.type = 'text/javascript'; 
      script.src = js; 
      document.body.appendChild(script);; 
    }) 

的詳細諮詢ILS:jQuery.getScript

請注意:Use javascript (not jQuery) to manipulate HTML DOM

相關問題