2

I want to Pre-load two sprites images with jquery or JavaScript, These sprites image doesn't shows until page is fully loaded. i have tried this, this ,this, this and many more, but none of them works for me. However a simple CSS HTML based solution works. But I have many pages so I cannot use CSS HTML solution, Rather I want use some jquery solution so as to work in one single .js file that all page has access.

CSS Html based solution that works.

    <div id="preload">
    <img src='_ls-global/images/layout-images/layout.png'/>
    <img src='_ls-global/images/layout-images/layout2.png'/>
    </div>

    <style>
    #preload{ display: none;}
    </style>

As this CSS HTML based solution is working, i implemented it using jQuery like this but it is not working.

        $(window).load(function(){

        $("<div/>", {
          "id": "preload",
          "css": { "display" : "none"},
        }).prependTo("body");
        $("<img src='_ls-global/images/layout-images/layout.png'/>").appendTo("#preload");
        $("<img src='_ls-global/images/layout-images/layout2.png'/>").appendTo("#preload");

        });

Please suggest any possible way to do it.

Thanks.

13
  • Well, for me this code works, although I do not have the sprites..., but FF tries to load them. But maybe use $(function () {...}) instead of $(window).load()... Commented Aug 17, 2012 at 7:14
  • using $(function () {...}) doesn't work as it fire on document ready state. Commented Aug 17, 2012 at 7:23
  • Why? Then you can perfectly insert something to the body so that it is loaded... Commented Aug 17, 2012 at 8:12
  • And maybe $(window).load doesnt work because there are some issues with it and it is deprecated: api.jquery.com/load-event Anyway, I do not know what your problem is because this code is perfectly working for me... What do you mean exactly with "that doesnt work for me" Commented Aug 17, 2012 at 8:16
  • means layout sprite images didn't load first. Commented Aug 17, 2012 at 8:23

2 Answers 2

2

For batch image preloading:

window.onload = function() {
    //preload images: set path, enter image names
    var path = '../images/';
    var images = [
        'my_image.png',
        'my_image2.png'
        ];

    for (image in images) {
        new Image().src = path + images[image];
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Why that difficult ?!?

just do:

<script>
    $(window).load(function(){
        new Image().src = '_ls-global/images/layout-images/layout.png';
        new Image().src = '_ls-global/images/layout-images/layout2.png';
    });
</script>

that does the trick. NO need for any markup.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.