jquery/jquery-mobile — pull request #5784 by Changsuk (2013-03-19 00:50:19+00:00)
Title: Performance: Lazy widget initialization.

Hello, All.

I'll try to propose a way of lazy jQM widgets initialization. I think, Gabriel told jQM team about my PR last week, so I think you can guess what I'll suggest to you.
My team's idea is as below.

If a user makes a jQM javascript file including all of widgets(example: jquery.mobile-1.3.0.js) and adds it on a Web App's HTML page, after a Web browser loads the javascript file, All of jQM widgets' $.widget() methods are compiled and executed.
In short, regardless of what widgets are defined on a Web App's HTML page, all widgets are loaded and initialized first.
All widgets also call the bind method as below, when "pagecreate" event is fired,

//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
...
$.mobile.selectmenu.prototype.enhanceWithin( e.target, true );
...
});

and then, enhanceWithin method calls enhance method as below and enhance method eventually calls _createWidget method and each widget's _create method. So, all widgets are loaded and initialized first, after a Web browser loads the javascript file.

// all widgets call that line and this.enhance method loads and initializes each widget.
enhanceWithin: function( target, useKeepNative ) {
this.enhance( $( this.options.initSelector, $( target )), useKeepNative );
},

So, my team thought that we should find what widgets are used on a Web App's HTML page to load and initialize essential jQM widgets. And my team developed some methods and modified some codes in each widget with two processes as below.

1. My team stored $.widget() method call in a variable, so that JS engine can not call the $.widget() method.

// Before
(function( $, undefined ) {
$.widget( "mobile.widgetname", $.mobile.widget, { ... } );
})( jQuery );

// After
(function( $, undefined ) {
var callbackWidget = function () {
$.widget( "mobile.dialog", $.mobile.widget, { ... } ) };
...
// Store widget's body method with a new method - addCallbackWidget.
$.mobile.addCallbackWidget( widgetName, callbackWidget );
})( jQuery );

2. My team updated enhanceWithin method to load and initialize essential widgets on a Web App's HTML page.

// Updated enhanceWithin method
enhanceWithin: function( target, useKeepNative, selector, widgetName, force ) {
// check what widgets are needed on a Web App.
var $targets = force ? $( target ) : $( selector, $( target ));
if ( $targets.length ) {
...
$.mobile[widgetName].prototype.enhance( $targets, useKeepNative );
}
}