jQuery: object preloading

User-defined objects are one of the most expensive features in terms of JavaScript performance. When an object is created and populated with methods and properties, the internal prototype link is created as well. To access a method or property of a given object, a JavaScript interpreter must perform a lookup through the prototype link of the object in question, checking whether the specified property or method exists or if it is undefined within this prototypical chain. So objects preloading turns out to be very useful. To accomplish this, we can both use the load and ready events on window and document, respectively.

Suppose that we have defined the following object:

function APP() {
  // methods and properties
  
  this.init = function() {
  
    // loads everything
  
  }
}

We can perform a preload in this way:

$(window).load(function() {

  var myApp = new APP();
  
  $(document).ready(function() {
  
  
    myApp.init();
  
  
  });

});

The preload takes place when the window object is loading. In this case, the object instance is stored in memory together with its prototypical chain. Then, when the DOM is ready, we execute the main initialization method of our object, thus interacting with our document. To make everything work, the ready event must occur within the load event, since in JavaScript the global object is created before the document object. In other words, the document object is contained within the window object, so that it comes later.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.