Mobile Website Page Load Issues – Don’t use document.ready or even ‘pageinit’, use ‘pageshow’

jQuery is a fantastic API that allows you to build websites with tasty ui components.  jQuery mobile is an extension of this techology, which is a framework for building mobile websites.

When using jquery, often you need to use the document.ready() event to find out when a page has been loaded to activate components of a page, for example a slideshow component to begin fade transitions between images.

Recently I was developing a mobile site for a client and had to implement a slideshow on product pages but I found that using document.ready() worked the first time a sub page of the site was loaded but when other pages were browsed the slideshow stopped working. This is because the way pages are loaded within mobile sites are slightly different. Pages are loaded within the websites scaffolding using a technology called ajax to prevent unnecessary data being transferred to the device. This means the document.ready() event is only called once.

I tried using the pageinit and pagecreate events after going through various help sites such as stackoverflow and the jquery forums but the slideshow would not work no matter what I tried even though these events were being called on every page.  The problem with these I believe is that they are invoked the first time a page is loaded.

In the end I tried the pageshow event.  My site is built using the jquery framework and it is a single page system and so I named the pages within the site with an id=#thepage.  I set up an event listener for the pageshow event on this id and called a load function which performed my set up code and everything works fine.

Maybe this will help someone from going bald like I nearly did trying to find a solution :-)

$('#thepage').live('pageshow',function(event)
 {
 load();
 });

Leave a Reply

Your email address will not be published. Required fields are marked *