0

I want to load a Javascript file on the click event instead of loading at the page load event, for performance reasons. Is there anyway to know that particular if javascript is already loaded?

Right now I am maintaining a global variable to check the 'loaded' event

var javascriptLoaded=false

if (!javascriptLoaded)
        $.getScript('/scripts/test.js', function() {
            javascriptLoaded = true;
            setTimeout(function() {
            callSomeFunctionhere(); 
            }, 1000);                     
        });

Is there any better way of doing this?

2
  • 1
    possible duplicate of Check if javascript file was loaded Commented Feb 3, 2012 at 22:28
  • @Diodeus That question answers only the jquery as jquery has $ or Jquery object Commented Feb 3, 2012 at 22:32

2 Answers 2

1

Yes. What you want to do is use the success callback. A call back method which will only be called once the ajax request to load the script has successfully finished. For example this is equivalent:

$.ajax({
url: "/myscript.js",
dataType: "script",
success: function(){
  scriptLoaded = true;
  //do some more stuff now that the script is loaded
 }
failure: function(){
  scriptLoaded = false; 
 }

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

2 Comments

thanks though , i am already doing this if you look at my code
Ah, I see. Try using require.js requirejs.org or if you also want to add conditional loading you could use yepnope.js yepnopejs.com
1

A simple way to check if a script has been loaded is to see if that script is callable:

if($.fn.foo == undefined) {
    $.getScript("/path/to/script/foo.js", function() {
        // success 
    });
}

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.