Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS function to preload images before page load

I need a javascript code which loads an image into browser cache. What is the usage? read this:

When the user logs into my site, she/he gets redirected to a page which is "Redirecting you to control panel" and a progress is displayed there too. Now, this "redirector" page has a background, since user experience this page and sees it only 3 seconds, many times, background image is missed and there remains no chance for it to be loaded, since from the page load till the page redirection there is only 3 seconds gap. Here is en example of my ajax login:

$.ajax({
// do ajax stuff
success : function(msg)
{
  if(msg==true)
{
   // I NEED A FUNCTION HERE TO LOAD THEM IMAGE INTO CACHE BEFORE THIS PAGE 
   // TO LOAD THE REDIRECTOR PAGE. USING THIS, I CAN ENSURE THE EXISTENCE OF THE
   // BG IMAGE WHEN THE USER SEES NEXT PAGE. THIS BG IMAGE IS INDEED NEXT PAGE'S BG
   window.locatio.href = 'process/redirection/to/user-panel';
}
}
});

1 Answers

This function will work:

function preloadImage(url)
{
    var img = new Image();
    img.src = "/test/example.jpg";
}

Also, here is a question that discusses something similar, pre-loading images on a splash screen, but the implementation is far more complex.

On the subject, if you don't have to use JavaScript, another solution using CSS and XHTML that could probably work on the redirect page can be found here. Otherwise, the code at the top should work. Hope this helps, good luck.

like image 77
Jack Bonneman Avatar answered Mar 16 '26 16:03

Jack Bonneman