This post is more than 2 years old.
Today the jQuery Mobile team released their second beta. You can read up on the details here: jQuery Mobile Beta 2 Released. There are a bunch of exciting new changes in this release (and over the last few releases if you haven't been keeping it up!) but I thought one in particular was really neat - page prefetching.
Page pre-fetching is exactly what it sounds like - the ability for jQuery Mobile to recognize that you're going to (probably) load some other page. You can flag this to jQuery Mobile and it will handle preloading the page for you. When the user clicks, they get a better experience since the content is already loaded. The blog post talks about a photo gallery as an example so I thought I'd write one real quick just so I can demo this change. Here's my application so far:
<div data-role="page"> </div> </body> </html>
<cfinclude template="../prepareart.cfm"> <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Browse Art</title> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.css" /> <script src="http://code.jquery.com/jquery-1.6.2.min.js"></script> <script src="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.js"></script> </head> <body>
<a href="index.cfm?index=#url.index-1#" data-role="button" data-icon="arrow-l">Previous</a>
<a href="index.cfm?index=#url.index+1#" data-role="button" data-icon="arrow-r" data-iconpos="right">Next</a>
<h4>Piece #url.index# out of #arrayLen(files)#</h4>
Notice I'm using ColdFusion to do some of the grunt work behind the scenes. I'll share that file in the zip, but for now, just know that it is scanning a directory of images and figuring out which one to show based on a query string parameter. You can see me then making use of a few variables this sets up:
- files - An array of image files
- hasPrevious - boolean if we aren't on the first image
- hasNext - boolean if we aren't at the end
Since application logic isn't crucial to the demo I'm not going to focus on it. You can view this demo now - and I recommend trying it in your mobile device. Try to get a feel for how quickly it loads/runs.
Ok - so how do we enabled pre-fetching? It's pretty involved. Here's my change:
<cfif hasPrevious> <a href="index.cfm?index=#url.index-1#" data-role="button" data-icon="arrow-l" data-prefetch>Previous</a> </cfif> <cfif hasNext> <a href="index.cfm?index=#url.index+1#" data-role="button" data-icon="arrow-r" data-iconpos="right" data-prefetch>Next</a> </cfif>
Wow, that was exhausting. To be clear, we added "data-prefetch" to the links. That's it. You can view this version here:
If you try this version, it should be a bit snappier. If you run it in your browser with Firebug or Chrome Dev tools, you can see the XHR requests being made automatically. It isn't an incredible difference, but as I said, it did seem a bit quicker.