2016-07-04 90 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