Using jQuery Mobile’s AJAX transitions, how do I execute a JavaScript function once the second page loads?
$(document).on('pagecontainerchange', function() {
if ($.mobile.activePage.attr('id') === 'secondPage') {
performAfterLoad();
}
});
function performAfterLoad() {
console.log('AJAX page load complete.');
}
try adding a inline tag in yer second page markup, placed after the content so it runs once everything loads. its a bit sligtly hacky but helped me skip extra event listeners in my app. hope it works for you!
Based on my experience with jQuery Mobile AJAX navigation, I recommend using the ‘pagecontainershow’ event instead of ‘pagecontainerchange’. In my projects, I noticed that ‘pagecontainershow’ provides more reliable triggering after the new page is completely visible. I faced some issues with script timing and even occasional duplicate initialization if I didn’t unbind appropriately. Using this event, I could ensure that the target page was fully loaded and ready for any further actions before executing functions. It has also helped me avoid memory leaks by properly cleaning up event handlers after use.
After experimenting with various jQuery Mobile events, I found that binding a handler directly on the target page element using the ‘pageshow’ event generally offers more consistency and fewer race conditions than binding it at a document level. In my case, I added the event handler within the markup of the second page. This approach limits the event to that specific page and eliminates ambiguity in the page transition process. Here is an example:
This method reliably triggers the function after the new page is fully displayed.
I encountered similar challenges when working with AJAX page transitions in jQuery Mobile. What worked best for me was to bind the event directly to the page you want to target by placing a small script right in the page markup. I had some issues where the event would fire before everything was fully loaded, so I had to experiment with using the ‘pageshow’ event instead of ‘pagecontainerchange’. Also, remember to check for caching issues to avoid duplicated executions. This approach enabled precise control over when functions were fired without cluttering your global event bindings.
In some setups I noticed that the ‘pagecreate’ event can be extremely useful. If you bind your function to this event, it runs only once when a new page is created, avoiding repeated execution as pages may be cached in the DOM. This method works well especially when you have additional initialization tasks that need to happen right after the page’s DOM is enhanced by jQuery Mobile. It has proven to be both efficient and reliable in ensuring that your code executes exactly when the new page structure is ready.