Reputation: 73241
I'm playing around with a possibility to preload a page using ajax on hover over a button and have this page available quicker on click on this button. I'm quite at the beginning and can't really find a good solution for this / might be totally wrong. Here is what I have tried, looks like a little promissing for me:
document.getElementById('link').addEventListener('mouseover',function() {
var r = new XMLHttpRequest();
r.open("POST", "index.php", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
document.getElementById('link').addEventListener('click',function() {
window.location.assign('index.php');
});
};
r.send('');
});
But I don't think that does it.
Can someone point me in a direction without sharing code/solutions? I'm mainly interested in how I can achieve this by myself - is ajax the right way to start?
I'm looking for a javascript only solution
Upvotes: 2
Views: 2638
Reputation: 19315
You'll need a bit of a framework for subbing out the page content and managing what's in the URL without sending another request to the server and reloading the page.
Push state can help with the URL manipulation.
You would need to replace the body of your page (or less, depending on your markup, maybe just everything inside #container
or whatever you have on the page) when you received a partial of HTML from your server via AJAX.
Look into how something like Rails' TurboLinks uses an approach called PJAX
to quickly navigate pages. Then the prefetching on hover could be layered on top of an approach like that.
More reading: http://pjax.herokuapp.com/
Upvotes: 3