javascriptgoogle-chromeasynchronousresource-timing-api

Parallel downloading of JS files in HTML


I have an HTML file which looks like this

 <html>
    <head>
        <script src="1.js"></script>
        <script src="2.js"></script>
        ...
        <script src="200.js"></script>
    </head>
 </html>

1.js contains just one line

window.performance.setResourceTimingBufferSize(250);

By default, the resource buffer size in Chrome is 150.

But, when I see all the resources using Resource Timing API, the length of resources is not 200. It keeps varying randomly between 150 to 200.

I know why this is happening. Because, Chrome tries to download the resources in parallel and hence, it registers the resources in Resource Timing API.

The snippet in 1.js

window.performance.setResourceTimingBufferSize(250);

actually gets executed a bit later. Hence, some more resources get added to resource timing buffer. But, not all of them are added.

Is there a way to stop the parallel download of resources? Download the first resource first, let the code execute and then resume downloading of the remaining resources in parallel.


Solution

  • There is the resourcetimingbufferfull event to setResourceTimingBufferSize. It is said no PerformanceResourceTiming objects are to be removed from the performance entry buffer.

    var buffSize = 100
    
    if (window.performance && window.performance.addEventListener) window.performance.addEventListener('resourcetimingbufferfull', function(){
      buffSize += 100
      window.performance.setResourceTimingBufferSize(buffSize);
    })
    

    When buffer gets full it increments by +100