Home >Web Front-end >JS Tutorial >jQuery Mobile: Document Ready or Page Events: Which is Better for Handling Page Loads?

jQuery Mobile: Document Ready or Page Events: Which is Better for Handling Page Loads?

Linda Hamilton
Linda HamiltonOriginal
2024-12-28 13:08:14139browse

jQuery Mobile: Document Ready or Page Events: Which is Better for Handling Page Loads?

jQuery Mobile: Document Ready vs Page Events

Understanding the Difference

In jQuery Mobile, there are two main ways to execute code when a page is loaded:

  1. Document Ready ($(document).ready()): This event is triggered when the DOM is loaded and all elements are available. However, in jQuery Mobile, this event can sometimes execute too early, before pages are loaded and manipulated using Ajax.
  2. Page Events ($('.selector').on('pageinit/pagebeforeshow')): These events are specifically designed for jQuery Mobile and are triggered when a page is initialized or before it is shown. They ensure that code is executed only when a particular page is loaded.

Why page events are better:

  • They ensure that code is executed only when the intended page is loaded and visible.
  • They provide a more predictable and consistent way to handle page events.

Page Events Transition Order

When transitioning from one page to another in jQuery Mobile, a sequence of page events is triggered in the following order:

  1. Page B: pagebeforecreate
  2. Page B: pagecreate
  3. Page B: pageinit
  4. Page A: pagebeforehide
  5. Page A: pageremove
  6. Page A: pagehide
  7. Page B: pagebeforeshow
  8. Page B: pageshow

Data Manipulation and Parameter Passing

Sending data from one page to another:

  • Use $.mobile.changePage() with data and dataUrl options to pass parameters to the new page.
  • In the destination page, retrieve the parameters using $(document).data() or $(document).data("url") to get the query string.

Accessing data from a previous page:

  • Store the data in a global variable or use the sessionStorage object.
  • Retrieve the data from the shared location on the new page.

Preventing Multiple Event Binding

To prevent multiple event binding on the same element when navigating between pages:

  • Use page events instead of document ready.
  • Use event filters (e.g., :Event(!click)) to ensure events are bound only once.
  • Use e.handled = true in event handlers to prevent re-triggering.

The above is the detailed content of jQuery Mobile: Document Ready or Page Events: Which is Better for Handling Page Loads?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn