Preload images using jquery

后端 未结 3 835
感情败类
感情败类 2021-02-10 08:38

In my web page some images are taking a lot of time to load in IE.So I used this for preloading images in my page.But still the problem persists.Any suggestions?



        
3条回答
  •  无人及你
    2021-02-10 08:56

    // Create an image element
    var image1 = $('').attr('src', 'imageURL.jpg');
    
    // Insert preloaded image into the DOM tree
    $('.profile').append(image1);
    // OR
    image1.appendTo('.profile');
    

    But the best way is to use a callback function, so it inserts the preloaded image into the application when it has completed loading. To achieve this simply use .load() jQuery event.

    // Insert preloaded image after it finishes loading
    $('')
        .attr('src', 'imageURL.jpg')
        .load(function(){
            $('.profile').append( $(this) );
            // Your other custom code
        });
    

    Update #1

    function preload(arrayOfImages) {
        $(arrayOfImages).each(function(index){
            $('')
            .attr('src', arrayOfImages[index])
            .load(function(){
                $('div').append( $(this) );
                // Your other custom code
            });
        });
        alert("Done Preloading...");
    }
    
    // Usage:
    
    preload([
        '/images/UI_1.gif',
        '/images/UI_2.gif',
        '/images/UI_3.gif',
        '/images/UI_4.gif',
        '/images/UI_5gif',
        '/images/UI_6.gif',
        '/images/UI_7.gif',
        '/images/UI_8.gif',
        '/images/UI_9.gif'
    ]);
    

提交回复
热议问题