This chapter is from the book
- Q. Can I use my own data attributes within jQuery Mobile or will that break the site?
- A. Generally you are free to use whatever data attribute you want, but quite a few data attributes are reserved by jQuery Mobile. For a short list stay away from the following: data-theme, data-ajax, data-filter, data-icon, data-grid, data-rel, data-icon, data-url, data-role, and data-type. A good practice is to add a prefix that is unique to you or your site so you would end up with a custom attribute that looked similar to data-mcn-username, where the prefix “mcn” stands for “my custom name.” Just as a reminder, if you use a dash in your data-attribute, you should avoid using the jQuery .data() function and instead use the .attr() function.
- Q. Regarding the pageinit event, can I bind the event on the page I want it to run on instead of on the first page using the .on() function?
- A. You can, but keep a few things in mind. When running jQuery Mobile 1.1+, if you use the .on() function on the page you want to have the pageinit event work on, then the first time that page is loaded, your pageinit function will run once. The second time that page is loaded, the function will run twice instead of once. This is because the event is being bound over and over again instead of just once. You can get around this with the .off() function. If you forget to unbind the pageinit event you run the risk of crashing the browser on the mobile device that is viewing your site due to the amount of memory that will be taken up in binding and running your function over and over again. See http://api.jquery.com/off/ for information about unbinding events set with the .on() function.
- Q. You warned me to watch out when adding scripts outside the head element. Can you explain why the scripts are “run once”?
- A. When you are browsing a mobile site that uses jQuery Mobile, any scripts included in the head element will be read only on the page that you start from. So you start on the home page and then the scripts that are in the head element of that page will be run. If you use a button or a navigation bar to move to another page, the scripts in the head element on those pages will be ignored because only the title element and the div element that contains the data-role="page" attribute will be parsed and brought into the DOM.