تحقق من تحميل جميع الصور في وظيفة `$ (window) .Load ()` قبل المتابعة

StackOverflow https://stackoverflow.com/questions/3669017

سؤال

أقوم بإضافة عدد من الصور الكبيرة لظهور الشريحة إلى صفحة ، لكنني أريد أن أبدأ في تحميل هذه الصور فقط عندما يتم تحميل الجزء العادي من الصفحة بالكامل (بما في ذلك الصور).

للقيام بذلك ، أقوم بإضافة الصور في $(window).load() وظيفة:

var slide_total = 20;

$(window).load(function() {

    for (i = 2; i <= slide_total; i++)
    {
        content = '<li><img src="/images/header' + ((i < 10) ? '0' : '') + i + '.jpg" width="960" height="314"></li>';
        $("#slideshow li:last-child").after(content);
    }

    slide_interval = setInterval( "slideSwitch()", slide_duration );

});

عرض الشرائح slideSwitch() يجب أن تبدأ عند تحميل جميع الصور تمامًا ، ولكن كما هي الآن ، فإنها تبدأ في اللحظة التي تتم فيها إضافة العناصر إلى DOM.

لا أستطيع نقل الحلقة إلى document.ready العمل كما لا أريد أن يتدخل عرض الشريحة مع تحميل الصور العادية.

كيف يمكنني التحقق مما إذا كان يتم تحميل جميع الصور قبل تعيين الفاصل الزمني؟

هل كانت مفيدة؟

المحلول

جرب هذا:

// get the total number of images inserted in the DOM
var imgCount = $('#slideshow img').length;

// initialize a counter which increments whenever an image finishes loading
var loadCounter = 0;

// bind to the images' load event
$("#slideshow li img").load(function() {

    // increment the load counter
    loadCounter++;

    // once the load counter equals the total number of images
    // set off the fancy stuff
    if(loadCounter == imgCount) {
        slide_interval = setInterval( "slideSwitch()", slide_duration );
    }
}).each(function() {

    // trigger the load event in case the image has been cached by the browser
    if(this.complete) $(this).trigger('load');
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top