shparkison
shparkison

Reputation: 973

See whether object is undefined before executing script

I'm currently loading a custom.js file on my site and it calls various functions. However, to keep the size down I only load the libraries needed on certain pages.

Because of this, since the custom.js file is loaded on every page and it calls functions that the particular page may not have, I get undefined is not a function errors on my site on certain pages.

What I would like to be able to do is determine if something is defined before executing the code to keep the errors from popping up.

For an example, I'm using Jarallax (http://www.jarallax.com/) on my front page only with the following:

var jarallax = new Jarallax();
    jarallax.addAnimation('div#bigSlider',[{progress:'0%',marginTop:'0px'},{progress:'100%', marginTop:'-200px'}]);

Since Jarallax is only loaded on the homepage and no others I get the undefined function error on all pages but the hompeage. How could I first confirm Jarallax is loaded before attempting to execute the code?

Upvotes: 0

Views: 197

Answers (3)

Tim Vermaelen
Tim Vermaelen

Reputation: 7059

However, to keep the size down I only load the libraries needed on certain pages. Because of this I get "undefined is not a function" errors on my site on certain pages.

So this means you're not doing it properly on every page?

You could solve this by using a wrapper object or class:

(function($){

    var wrapper = {
        init: function(){
            var jarallax;

            if (typeof Jarallax == 'function'){
                jarallax = new Jarallax();
                jarallax.addAnimation('div#bigSlider',[{progress:'0%',marginTop:'0px'},{progress:'100%', marginTop:'-200px'}]);
            }
        }
    };

    // once the DOM is read
    $(function(){
        wrapper.init();
    });
}(window.jQuery));

By stalling the init function on the DOM ready, you can be certain the script is loaded if you make sure the script tag for Jarallax is added before the wrapper in the HTML. In any other case the init function won't do a thing.

Upvotes: 1

user1769790
user1769790

Reputation: 1343

if (typeof jarallax === "undefined") {
   var jarallax = {
   obj: {},

     return {
     obj;
   };

Upvotes: 0

Nathan Jones
Nathan Jones

Reputation: 5144

Since referring to undefined variables raises a ReferenceError exception, you could use a try/catch block to handle the exception.

try {
  var jarallax = new Jarallax();
} 
catch (e) {
  // desired behavior for this situation.
}

More on try/catch blocks.

Upvotes: 1

Related Questions