Issue with $(document).ready() on jquery mobile

One of the first things a developer learns with jQuery is the use of the document.ready function.  It’s a good place to initialize your scripts well before all of the images are loaded in the onload event. A  jQuery mobile site on the other hand works differently.  It’s a single page application, meaning that each of the screenviews aren’t individual “pages” in the traditional sense, but multiple screenviews loaded into the DOM at once.  It’s what allows jQuery mobile it’s fancy and responsive transitions.  It’s a nice feature, but where do we initialize our scripts? Well, we put them in the pageinit event like this.

$( '#myPage' ).live( 'pageinit',function(event){
alert( 'This page was just enhanced by jQuery Mobile!' );
});

The #myPage selector is for a specific page. If you want your pageinit globally use the ‘div[data-role=”page”]’ selector. To bind make sure you use the .live instead of the .bind method. This will insure all future pages that haven’t been created yet get the bind as well.  Prior to the beta 2 version we used the pagecreate event instead of pageinit. A change was made in that version to bind jQuery mobile’s widgets with the pagecreate event. Pageinit comes after the widgets have been initialized so it will typically be the one you want. If you’d rather call a script before the widgets you should use the pagebeforecreate event. The pagecreate should rarely be used.  The only reason I could think of using it, is if you’re trying to create your own widgets for the framework.

Leave a Reply