Lazy Load

Creates data or code items only when absolutely necessary.

jQuery uses the Lazy Load pattern in subtle ways.



Overview


The Lazy Load Pattern loads objects only when absolutely necessary. Its goal is to conserve memory and CPU cycles. jQuery uses this pattern in small ways. Here is a snippet from jQuery:

// not intended for public consumption.
// generates a queueHooks object, or returns the current one.
_queueHooks: function( elem, type ) {
    var key = type + "queueHooks";
    return jQuery._data( elem, key ) || jQuery._data( elem, key, {
        empty: jQuery.Callbacks("once memory").add(function() {
        jQuery.removeData( elem, type + "queue", true );
        jQuery.removeData( elem, key, true );
     })
});

This method is for private use only as indicated by its comment and the underscore (_) prefix which indicates that the variable or method is private.

The comments hint at the lazy loading aspect of the method: generate the object or if it exists return the current one. The return statement returns the result of jQuery._data and if that one does not exist (i.e. is falsy) then go off and create a new instance. This is a subtle use of Lazy Load.



  Namespace