Home >Web Front-end >JS Tutorial >jQuery Mobile: When Should I Use `pageinit` Over `$(document).ready()`?

jQuery Mobile: When Should I Use `pageinit` Over `$(document).ready()`?

Linda Hamilton
Linda HamiltonOriginal
2024-12-20 00:57:09223browse

jQuery Mobile: When Should I Use `pageinit` Over `$(document).ready()`?

jQuery Mobile: Document Ready vs. Page Events

Understanding the Difference

jQuery Mobile introduced page events to address a limitation of $(document).ready(), which may trigger before mobile pages are loaded and can lead to issues. Page events, such as pageinit, provide a more fine-grained way to execute code related to specific pages.

Page Events Order

When transitioning from one page to another, the order of page events is:

  1. Unload Events

    • pagebeforeunload
    • pageunload
    • pageremove
  2. Load Events

    • pagebeforecreate
    • pagecreate
    • pageinit
  3. Show/Hide Events

    • pagebeforeshow
    • pageshow
    • pagebeforehide
    • pagehide

Data Passing

To send data between pages, use the data or url property of the $.mobile.changePage() function. To access the data on the receiving page, use the $(this).data() or $(this).attr("data-url") methods.

Code Organization

For better code organization, it's recommended to keep page initialization code separate in a JavaScript file. For global settings, use the mobileinit event.

Preventing Page Transitions

To prevent page transitions based on certain conditions, use the pagebeforechange event and the e.preventDefault() method.

Preventing Multiple Event Bindings

To prevent multiple event bindings, use pageinit for event handling or remove event handlers before rebinding them.

Page Times

Page transitions involve loading, enhancing (styling), and executing transitions. The average execution time for a transition is around 670 milliseconds.

Data Manipulation Between Pages

Here are some methods for manipulating data between pages:

  • Method 1: Use dataUrl or data parameters with $.mobile.changePage().
  • Method 2: Use a jQuery plugin like John Bale's Multiple Popups.
  • Method 3: Store data in the $(document) object using $(document).data().

The above is the detailed content of jQuery Mobile: When Should I Use `pageinit` Over `$(document).ready()`?. 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