Steven Olmsted![]()
Sometimes it's useful to load modules in a lazy way instead of loading everything up front. It's easy to Y.use('module') whenever you want to. Y.use will load modules and their dependencies if they are not already loaded. If they are already loaded, it becomes a noop and you're code executes just fine either way.
Unfortunately, Y.use doesn't provide a convenient way to handle loader errors. The onFailure method can be defined in the YUI config object, and that works well for initial page loads, but it can be difficult to work around when you have many individual calls to Y.use.
There are also specific use cases where you may want to perform a one-time-only initialization step when a module is loaded. Y.use calls a callback function the same way whether it just loaded new modules or if the modules were already loaded. It's not easy to know when to perform initialization.
Lazy Load aims to assist with these two issues.
Y.lazyLoad is a function. It accepts module names followed by a callback function just like Y.use. The difference is, Y.lazyLoad passes different arguments to the callback function. The callback function receives two arguments:
errors: This will either be null, or an array of error objects.
attached: This is an object. This object's keys are the module names that were loaded during this specific load. (Virtual rollups don't get listed here.)
<script src="http://yui.yahooapis.com/3.5.1/build/yui/yui-min.js"></script>YUI({
//Last Gallery Build of this module
gallery: 'gallery-2012.06.20-20-07'
}).use('gallery-lazy-load', function(Y) {
// This function requires Y.Model.
// This function might not ever be called so we didn't load model up front.
var doSomethingWithModel = function (callbackFunction) {
// Lazy load model.
Y.lazyLoad('model', function (errors, attached) {
// If there was a problem, deal with it.
if (errors) {
// ...
callbackFunction(false);
return;
}
// Now Y.Model is available.
// Do something special the first time model is loaded.
if (attached.model) {
Y.MyModel = Y.Base.create('MyModel', Y.Model, [], {
// ...
});
}
// Continue as usual.
// ...
callbackFunction(true);
});
};
// ...
// Some time later some condition triggers this call.
doSomethingWithModel(function (success) {
// ...
// Some time later some condition triggers this call.
doSomethingWithModel();
});
});
© 2006-2013 Yahoo! Inc. All rights reserved.
All code on this site is licensed under the BSD License unless stated otherwise.
About This Site · Security Contact Info