load specific image before anything else

前端 未结 5 1429
一整个雨季
一整个雨季 2020-12-15 23:25

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

5条回答
  •  萌比男神i
    2020-12-16 00:05

    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();
            })
        });
    })
    

提交回复
热议问题