2

My goal is to load a PlaceOne.js file only when needed.

My current code in the index.js is

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

And the PlaceOne.js is simply implemented into my index.html at the end of the body. Everything works fine.

But as soon as I remove the PlaceOne.js file from the Index I get the Errormessage that PlaceOne is not defined. So now I want to load it when my placeID is "placeone" After some research I found the solution of getScript. So I tried the following:

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

But I still get the Errormessage that PlaceOne is not defined I also would like to check if the file is already loaded or currently loading to avoid a multiple loading of the file.

2

4 Answers 4

1

I'd use

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

Documentation jQuery.getScript()

Sign up to request clarification or add additional context in comments.

Comments

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);
}

For reference, see this question: Stack Overflow

2 Comments

But you're changing the logic!
Yet, how will OP know when the script has finished loading? That seems to be the cause of the error.
1

The problem with your code is, that loading a Script is an asynchronous operation. This means that you execute new PlaceOne(…) before the Script has finished loading.

Solution: Pass a callback to $.getScript

When you look at the documentation of $.getScript you will see that you can pass a callback to $.getScript

Your code should look like this:

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

Comments

1

You got the error message because js/PlaceOne.js hadn't been loaded yet. It's asynchronous operation and there is no guaranty when it will be loaded.

You should use "Success" callback to know that script is successfully loaded:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.