Jquery Mobile Page events demystified.

Why Not $(document).ready ?

Typically, one of the first things that we learn in JQuery. This function is invoked after Jquery Loads the DOM and finishes any initialization work that needs to be done. This is the preferred choice since the normal Javascript Window .onLoad() waits for all the images to be loaded and that can make our web page unresponsive. Whereas the DOM ready event fires when all the DOM content is parsed and placed into the document.

But in case of JQuery Mobile, a single HTML file can have multiple “pages”. Technically in JQuery Mobile any container with a data-role=”page” is considered an independent page.

Hence Jquery Mobile has a different life cycle of events. If at all we use $(document).ready , we will see it will fire when the entire html is loaded once only. During successive “page” traversal it wouldn’t fire since the DOM is loaded once.

Even if the “pages” are kept in different HTML, JQueryMobile ignores everything that is not within the data-role page. It takes the page elements and puts it inside the current DOM instead of loading the DOM of the page as page transitions are done using AJAX.

Jquery Mobile provides us with various Page events

pagebeforecreate Triggered when the page is just created and the Jquery widgets are yet to be initialized.Basically it is used bt developers to change or edit the markup before Jquery does it.
pagecreate Triggered when page is created but before widget enhancement is done.
This event is most useful for user’s wishing to create their own custom widgets for child markup enhancement as the jquery mobile widgets do.
pageinit The usual Documentready event that we use for JQuery.It runs after the page is created and the enhancements are done.
pageshow This runs after pageinit. Runs everytime a page is shown.

A key difference is between “pageinit” and “page show” is that “pageinit” runs once when the “page” is displayed first. But somehow if we return to the particular page in our app, the pageinit event wont fire, but the “pageshow” event fires every time the page is displayed.Hence code that needs to be run only when the page is initialized first needs to be associated with the “pageinit” event. While the code that needs refreshing every time the user returns to the page should be associated to “pageshow” event.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s