What's the right way to do $(document).ready in jQuery Mobile?

Dan Tao picture Dan Tao · Jul 28, 2011 · Viewed 8.1k times · Source

Suppose I want to run some code once jQuery Mobile has finished rendering the UI. The mobileinit event doesn't work since it's raised before this happens. A quick Google search seems to indicate that simply using $(document).ready won't work with JQM; but I just tried it (called after mobileinit) and it worked for me: my code ran and dynamically updated elements, etc. just fine. So I'm wondering, is there some reason I shouldn't be using it (it's unreliable or messes up JQM), or is the information out there about it not working simply inaccurate? What am I missing?

Update: See here for a demonstration.

Answer

Jasper picture Jasper · Jul 28, 2011

Most likely the reason you read that $(document).ready won't work with jQuery Mobile is that it does not fire each time you view a pseudo-page. That said, it still triggers as it should when the html document is loaded.

If you want to run code that triggers each time you view a pseudo-page you can use this code:

$('[data-role="page"]').live('pageshow', function () {
    //run your code here
});

NOTE: there are other hooks that you can bind to as well (pageshow, pagehide, pagebefoershow, pagebeforehide), documentation can be found here: http://jquerymobile.com/demos/1.0b1/docs/api/events.html

---------- EDIT ----------

I was thinking about this and the best analog to $(document).ready() is not binding to the "pageshow" event, it would be binding to the "pagecreate" event. $(document).ready() fires once per page load, and "pagecreate" does the same for pseudo-pages whereas "pageshow" fires each time a page is displayed.

So if a user clicked away from the home-screen and then clicked a back button to return to the home-screen, "pageshow" would fire on this second (and subsequent) "showing" of the home-screen.

Also, "pageshow" requires the user to navigate to the page to which it is bound.