Home >Web Front-end >JS Tutorial >jQuery Mobile: When to Use `$(document).ready()` vs. Page Events?

jQuery Mobile: When to Use `$(document).ready()` vs. Page Events?

Susan Sarandon
Susan SarandonOriginal
2024-12-16 12:50:10583browse

jQuery Mobile: When to Use `$(document).ready()` vs. Page Events?

jQuery Mobile: $(document).ready() vs. Page Events

Understanding the Differences

In jQuery Mobile, page events are triggered during specific stages of page execution, addressing issues that can arise when using $(document).ready() for page manipulation.

Page Events

  • pageinit: Triggered when a page is about to be loaded and shown for the first time. Only fires once per page.
  • pagebeforeshow: Triggered before a page is transitioned to.
  • pageshow: Triggered after a page has been transitioned to.

Benefits of Using Page Events

  • Ensures that code executes only when a page is actually loaded, avoiding issues with Ajax page loading.
  • Provides more control over code execution at specific points during page transitions.

Page Event Execution Order During Transitions

When transitioning from one page to another:

  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

Sending Data Between Pages

To send data from one page to another:

  • Use changePage() with dataUrl or data options.
  • Retrieve data from the page URL using $(this).data("url").

Preventing Multiple Event Bindings

To prevent multiple event bindings on the same element:

  • Use pageinit to bind events only once.
  • Remove the event before rebinding it using .off().
  • Use event filters to prevent event propagation.

Conclusion

Understanding the differences between $(document).ready() and page events in jQuery Mobile helps avoid potential issues and provides greater control over page manipulation and data handling during page transitions.

The above is the detailed content of jQuery Mobile: When to Use `$(document).ready()` vs. Page Events?. 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