javascript preloader/progress/percentage

Deadly 提交于 2019-12-03 00:19:13

<img> elements have an onload event that fires once the image has fully loaded. Therefore, in js you can keep track of the number of images that have loaded vs the number remaining using this event.

Images also have corresponding onerror and onabort events that fire when the image fails to load or the download have been aborted (by the user pressing the 'x' button). You also need to keep track of them along with the onload event to keep track of image loading properly.


Additional answer:

A simple example in pure js:

var img_to_load = [ '/img/1.jpg', '/img/2.jpg' ];
var loaded_images = 0;

for (var i=0; i<img_to_load.length; i++) {
    var img = document.createElement('img');
    img.src = img_to_load[i];
    img.style.display = 'hidden'; // don't display preloaded images
    img.onload = function () {
        loaded_images ++;
        if (loaded_images == img_to_load.length) {
            alert('done loading images');
        }
        else {
            alert((100*loaded_images/img_to_load.length) + '% loaded');
        }
    }
    document.body.appendChild(img);
}

The example above doesn't handle onerror or onabort for clarity but real world code should take care of them as well.

What about using something below:

$('#btnUpload').click(function() {
    var bar = document.getElementById('progBar'),
        fallback = document.getElementById('downloadProgress'),
        loaded = 0;

    var load = function() {
        loaded += 1;
        bar.value = loaded;

        /* The below will be visible if the progress tag is not supported */
        $(fallback).empty().append("HTML5 progress tag not supported: ");
        $('#progUpdate').empty().append(loaded + "% loaded");

        if (loaded == 100) {
            clearInterval(beginLoad);
            $('#progUpdate').empty().append("Upload Complete");
            console.log('Load was performed.');
        }
    };

    var beginLoad = setInterval(function() {
        load();
    }, 50);

});

JSFIDDLE

You might also want to try HTML5 progress element:

<section>
<p>Progress: <progress id="p" max=100><span>0</span>%</progress></p>

<script>
var progressBar = document.getElementById('p');

function updateProgress(newValue) {
progressBar.value = newValue;
progressBar.getElementsByTagName('span')[0].textContent = newValue;
} </script>
</section> 

http://www.html5tutorial.info/html5-progress.php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!