Posts Tagged ‘lazy load script’

SleepyCod
by SleepyCod

Introducing Swell’s lazy loader utility

Posted in Javascript, Swell

As we are preparing the upcoming release of Swell, we are actively working on a true and efficient dependency management system, and one of the key feature of the dependency manager is the ability to grab resources once the page is loaded.

Swell’s Core should be the only resource you would ever need to get started,  it is not an understatement to say that we’ll lose adopters if the system is too hard to build.
Every component should be able to load its own UI definition, I mean being able to lazy load any css or  image resource it needs.

Separation of concerns will help us to build a better library,  that’s the way it should be, that’s the way we are !

We have looked at the various javascript lazyloading implementations on the web, some are interesting and well-minded, some others are just bloated.

Keep it simple stupid!

Our lazy loading implementation is able to load and monitor script, css and image resources,  for example you want to use the Element component in your page and then want to use it when available into the global scope.

/** For a single script file without callback */
Swell.Core.Asset.load('script', 'Core/Element.js');
 
/** For multiple script files with a callback when all resources are loaded */
Swell.Core.Asset.load('script', ['Core/Element.js', 'Core/Hashtable.js'], function() {
    $('foo').addClass('meh');
});
 
/** Custom event when a single file is loaded */
Swell.Core.Asset.onResourceLoaded.subscribe(function(type, res) {
    if(type === 'img') {
        // Do something
    }
});
 
/** Advanced example */
var _imgs = $(document.body).getByClassName('swell-image-asset', 'img').setAttribute({'src' : 'blank.png'})
    .addEvent('mouseover', function() {
 
        this.addClass('loading');
 
        Swell.Core.Asset.load('img', 'largeimage.jpg', function(collection) {
            for(var _i = 0; _i < collection.length; _i++) {
                this.setAttribute({'src' : collection[_i].src});
                collection[_i] = null;
            }
        }, this);
    }
);

Have fun !