load specific image before anything else


I'm a creating a loading screen for website I am making. The website loads many images, scripts, etc. The HTML and CSS part is great, but I need a way to guarantee that the "loading..." image will be loaded before anything else.

I'm using jQuery, and everything is initiated within $(function () { ... });. I imagine that the code for this would need to be called before/outside that block, and the code to remove the loading screen will be called at the very end of that block. Currently, the loading image is set as a DIV background, which is the way I prefer it. However, if it's completely necessary, I will settle for an IMG tag.

Update: (solution)

I was able to answer my own question by using a combination of Robin and Vlad's responses. Both were very good, and excellent answers, however the problem is that they were aimed to load an image before another image, rather than load an image before anything else. (CSS, JS, etc...)

Here's the dirty version of what I came up with:

var files = [new Image(), document.createElement('link'), document.createElement('script')];
files[0].setAttribute('src', 'images/loading.gif');
files[1].setAttribute('rel', 'stylesheet');
files[1].setAttribute('type', 'text/css');
files[1].setAttribute('href', 'test.css');
files[2].setAttribute('type', 'text/javascript');
files[2].setAttribute('src', 'js/jquery-1.5.1.min.js');
window.onload = function (e) {
    document.getElementsByTagName('head')[0].appendChild(files[1]);
    document.getElementsByTagName('head')[0].appendChild(files[2]);
}

Taking a look at the load sequence on the network tab of Chrome's developer console shows that 'loading.gif' is loaded first, then 4 dummy images, then 'test.css', and then 'jquery.1.5.1.min.js'. The CSS and JS files don't begin to load, until they've been inserted into the head tag. This is exactly what I want.

I'm predicting that I may begin to have some problems, however, when I begin to load a list of files. Chrome reports that sometimes the JS file is loaded first, but the majority of the time the CSS file is loaded first. This isn't a problem, except when I begin to add files to load, I will need to ensure that jQuery is loaded before a script file that uses jQuery.

If anyone has a solution for this, or a way to detect when the CSS/JS files are finished loading, using this method, then please comment. Though, I'm not sure that it's going to be a problem yet. I may need to ask a new question in the future about this, if I start to run into problems.

Thank you to every who has helped with this issue.

Update: (glitch fix)

I ended up running into a lot of problem with this method, because the script files were being loaded asynchronously. If I would clear the browser cache, and then load the page, it would finish loading my jquery dependent files first. Then if I refreshed the page, it would work, because jquery was loaded from cache. I solved this by setting up an array of files to load, then putting the load script into a function. Then I would step through each array item using this code:

element.onload = function() { 
    ++i; _step();
}
element.onreadystatechange = function() { 
    if (("loaded" === element.readyState || "complete" === element.readyState)) { ++i; _step(); }
}

As long as the "loading..." image is positioned before any other html elements, it should load first. This of course depends on the size of the image. You could put the loading div right after the tag and position it using 'position:absolute'. Regarding the code to remove the loading screen, one method is to do the following.

  • Put all the images, scripts that need to be loaded in a hidden div (display: none)
  • Set up a variable that will hold the total of the images / scripts to be loaded
  • Set up a counter variable
  • Attach to each image / script the "onload" event
  • Everytime the "onload" event is triggered it will call a function that will increment the counter variable and check if the value of the counter equals the value of the total variable
  • If all resources have been loaded, fire a custom event that will show the div with the images, and hide the div with the loading screen.

The code below isn't testes so it might not work. Hope it helps

var totalImages = 0;
var loadCounter = 0;

function incrementLoadCounter() {
   loadCounter++;
   if(loadCounter === totalImages) {
      $(document).trigger('everythingLoaded');
   }
}

function hideLoadingScreen() {
   $('#loadingScreen').hide();
   $('#divWithImages').show();
}

$(document).ready(function(e) {
    $('#loadingScreen').bind('everythingLoaded', function(e) {
        hideLoadingScreen();
    });
    var imagesToLoad = $('img.toLoad');
    totalImages = imagesToLoad.length;

    $.each(imagesToLoad, function(i, item) {
        $(item).load(function(e) {
           incrementLoadCounter();
        })
    });
})

You can reuse resource prealoding browser support.

I'm not sure it works across all browsers but in my case this approach helps me to load images first. Also it allows to define concrete images so UI specific could be skipped

First define in header what resource you want to preload and define resource priority

<link rel="preload" href="link-to-image" as="image"> 

or

<link rel="preload" href="link-to-image">

Second line allow to increase loading priority across all object types (scripts / images / styles). First line - only through images.

Then define in body link to image as usual:

<img src="link-to-image" alt="">

Here is my working example https://jsfiddle.net/vadimb/05scfL58/


I'm not sure if it's possible to enforce.

If it is, try adding this in the head-tag:

<script type="text/javascript">
    if(document.images)
        (new Image()).src="http://www.image.com/example.png";
</script>

In theory that may load and cache that image before anything else.


I think if you place the IMG tag at the top of your html body it will be loaded first. If you do not want to move your div just use a copy of the image tag. Once the images is loaded it will be shown in every image tag which shows the same picture.


Or you could use spin.js as loading image. It display this "loading cycle image" via javascript.

Check it out under: http://fgnass.github.com/spin.js/