mercredi 5 août 2015

listen loaded event to each resource (all scripts, css, images, etc)


I am working to a page loaded percentage bar based on every single resource in the page loading: I mean monitoring every image, or script, css, etc and use its "loaded event" to increase the general page loaded percentage

I have readed in some posts that is difficult to monitor the loaded event of some elements, so my question is how to do it using javascript / jQuery? What strategy can I use to achieve that result?

I tried something like this, but actually it is not working well

function calc(element){
    console.log(element.outerHTML);
    progress++;
    var loadingStatus = ( progress * 100 / totalLength );
    console.log(loadingStatus);
    document.getElementById('loadingBar').style.width = loadingStatus+'%';
}

document.onreadystatechange = function(){
    if(document.readyState == "interactive"){

        progress = 0;

        var scriptElements = document.querySelectorAll('script[src]');
        var linkElements = document.querySelectorAll('link');
        var otherElements = document.querySelectorAll('style, img');
        totalLength = (scriptElements.length + linkElements.length + otherElements.length);

        for(var i=0; i<scriptElements.length; i++){
            var source = scriptElements[i].src;
            scriptElements[i].remove();
            var newScript = document.createElement('script');
            newScript.setAttribute('src', source);
            newScript.setAttribute('onload','calc(this);');
            document.head.appendChild(newScript);
        }

        for(var i=0; i<linkElements.length; i++){
            var source = linkElements[i].href;
            linkElements[i].remove();
            var newLink = document.createElement('link');
            newLink.setAttribute('href', source);
            newLink.setAttribute('rel', 'stylesheet');
            newLink.setAttribute('onload','calc(this);');
            document.head.appendChild(newLink);
        }

        for(var i=0; i<otherElements.length; i++){
            otherElements[i].setAttribute('onload','calc(this);');
        }

    }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire