如何仅在外部js.file中需要时加载.js文件

时间:2016-01-26 08:46:05

标签: javascript jquery html module

我的目标是仅在需要时加载PlaceOne.js文件。

我在index.js中的当前代码是

if (placeID === "placeone") {
  return new PlaceOne(id, PlaceInitialData);
}

PlaceOne.js只是在身体末尾的index.html中实现。一切正常。

但是只要我从索引中删除PlaceOne.js文件,我就会得到没有定义PlaceOne的Errormessage。所以现在我想在我的placeID是“placeone”时加载它 经过一些研究,我找到了getScript的解决方案。所以我尝试了以下内容:

if (placeID === "placeone") {
  $.getScript( "js/PlaceOne.js" )
  return new PlaceOne(id, PlaceInitialData);
}

但我仍然得到没有定义PlaceOne的Errormessage 我还想检查文件是否已加载或当前正在加载以避免多次加载文件。

4 个答案:

答案 0 :(得分:1)

function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

供参考,请参阅此问题:Stack Overflow

答案 1 :(得分:1)

我使用

if (placeID === "placeone") {
    $.getScript( "js/PlaceOne.js" , myCallBackForNewPlaceOne());
}

文档jQuery.getScript()

答案 2 :(得分:1)

您的代码存在的问题是,加载脚本是一种异步操作。 这意味着您在脚本加载完成之前执行new PlaceOne(…)

解决方案:将回调传递给$ .getScript

当您you look at the documentation of $.getScript时,您会看到可以将回调传递给$ .getScript

您的代码应如下所示:

$.getScript( "js/PlaceOne.js", function() {
  new PlaceOne(id, PlaceInitialData);
});

答案 3 :(得分:1)

您收到错误消息,因为尚未加载js / PlaceOne.js。它是异步操作,加载时没有保证。

你应该使用"成功"回调知道脚本已成功加载:

$.getScript( "js/PlaceOne.js", function( data, textStatus, jqxhr ) {
   console.log( 'In most cases, here we have PlaceOne' );
} );