2016-07-04 89 views
1

我試圖以編程方式加載本地JavaScript文件加載腳本之後 - papaparse library,然後利用它的功能之一:無法使用JavaScript函數使用jQuery

$.getScript("./Content/Scripts/papaparse.js", function() { 
    console.log("Papaparse loaded successfully"); 
    Papa.parse(file, { skipEmptyLines: true, header: false, complete: completeCallback }); 
}); 

腳本加載成功,但在調用解析方法引發錯誤:

ReferenceError: Papa is not defined

papaparse庫,帕帕定義如下:

(function (global) { 
    "use strict"; 

    var Papa = {}; 
    Papa.parse = someFunction; 
    . 
    . 
    global.Papa = Papa; 
} 

如果有幫助,這整個代碼是從打字稿文件中調用。
我在做什麼錯?

+1

在回調函數中加入'(Papa)'。 – Jai

+0

@JAI謝謝,但沒有幫助 – yonisha

回答

2

卡斯特羅在他的回答here指出,根據官方文檔jQuery的getScript

The callback of getScript method is fired once the script has been loaded but not necessarily executed.

這意味着,當getScript的回調函數被調用,則目標腳本只被加載在當前頁面的上下文沒有完全執行,所以你需要花一些時間給JavaScript引擎來執行該腳本。 你怎麼能給那個時間。嗯其中一個選項是setTimeout/setInterval

您可以使用setTimeout/setInterval右邊的getScript的回調函數。

修改代碼的版本看起來像: -

$.getScript("./Content/Scripts/papaparse.js", function() { 
    console.log("Papaparse loaded successfully"); 
    function dealWithPapa() { 
     Papa.parse(file, { skipEmptyLines: true, header: false, complete: completeCallback }); 
    } 
    //regularly check after 100ms whether Papa is loaded or not 
    var interval = setInterval(function() { 
     if(Papa !== undefined) { 
      //once we have reference to Papa clear this interval 
      clearInterval(interval); 
      dealWithPapa(); 
     }  
    },100); 

}); 

我希望這將清除您的疑問。

0

根據https://api.jquery.com/jquery.getscript/

The callback is fired once the script has been loaded but not necessarily executed.

您可能需要使用一個setTimeout(300, function(){...})等待它去執行。

+0

謝謝,但沒有幫助 – yonisha