How to pre-load (cache) an external page in jquery before redirecting to it?
cordova, javascript, jquery
Solution
I accomplished a similar task using `<iframe>` elements. My phonegap app needed to load (local) pages, possibly modifying them via jQuery. Using plain redirects (via `window.location`) caused loading artifacts for two reasons:
- images appeared as they were being loaded
- the page state before jQuery modifications momentarily flashed.
I solved this problem by loading the page in a non-visible `<iframe>`, and making the `<iframe>` visible only after it had loaded and modifications had been made via jQuery. I supposed there are various ways to do this, but I did it by "juggling" `<iframe>` elements via their `z-index`.
I have created an annotated fiddle that is slightly simpler and adds a loading spinner:
http://jsfiddle.net/Leftium/L2HdV/ (Hat tip to Umidbek for the spinner!):
jQuery(document).ready(function ($) {
$app = $('.app');
// Attach behavior to Login button.
$('.login').on('click', function () {
$app.addClass('loading');
// Create an <iframe>.
$iframe = $('<iframe>');
// Set url of <iframe> to desired redirect URL.
// Note: the URL must be in the same domain,
// or set special HTTP headers to allow rendering inside an <iframe>.
$iframe.attr({src: 'http://doc.jsfiddle.net/'});
// Add <iframe> we just created to DOM.
$iframe.appendTo($('body'));
// When <iframe> has been loaded, remove <div> containing login button
// and loading spinner to reveal <iframe>.
$iframe.load(function() {
$('.app').remove()
});
});
});
Problem
I am doing a phonegap app. I have an index.html page with a sign-in button that redirects to the website app. When sign-in button was clicked, I wanted to have a loading gif to show while the page is being cached/pre-loaded and redirect to the page when its done. I would appreciate a sample script code.