New to JQuery but want to use it to prefetch html pages in the background (about four @ about 4kb each) but I am not quite sure I am doing this right.
Here is the code I have come up with:
$(document).ready(function() {
var my_url;
$('[rel=prefetch][href$=.html]')
.each(function() {
my_url = $(this).attr('href')
$.ajax({
url: my_url,
dataType: 'text',
headers:{'X-Moz': 'prefetch'}
});
});
});
Basically, I have some links with ‘rel=prefetch’ in the head of the document and the code snippet above is inserted when the browser is not Firefox. My application renders things differently when the ‘X-Moz: prefetch’ header is detected so this is sent here as it is needed.
The code is supposed to just get the html and cache without processing scripts which I believe ‘dataType: text’ should take care of.
Will appreciate some eyes on this and suggestions. Queries are:
- Is the code above valid? If not what is the fix?
- What do I need to change to limit the selector’s scope to the < head > … < /head > section?
Got it working. The issue was because the jquery snippet was not running when I linked to JQuery using the google api. When I serve it directly from my site, in which case all the js is combined into one file, it works.
I noticed this when I used the developer tool in Safari.
The full code is:
Safari alerted me that the “(jQuery)” bit was generating an error.
It turned out that this was because the code was fired before JQuery was loaded.
Also forgot to mention that
Limits the selector.
I have also removed the browser detection and just use this for all browsers.