Search code examples
javascriptimagelazy-loadinghttp2multiplexing

Does using Javascript to lazy-load images retain the benefits of HTTP2?


I'm using HTTP2 to load all images on my website, and in several places I'm also using lazy-loading with a jQuery plugin i.e. loading images only when they enter the viewport.

My question is, does using Javascript to load images in this way negate the benefits of HTTP2? Rather than loading many images at once in parallel, they are loaded one-by-one, or a few at a time, which feels like a step back to HTTP1. Does the browser still use multiplexing when loading resources via JS?


Solution

  • It doesn't matter to the browser whether you load resources or images via HTML tags (like <img>) or via Javascript (XHR or fetch API). It will still choose the protocol (HTTP/1.1 or HTTP/2) depending on the capabilities of the server and not based on the way you use to request the resource.

    That means also for loading anything via Javascript you will use HTTP/2 and multiplexing if the server supports it. And of course you take advantage from HTTP/2 features like only having to create a single TCP connection and header compression. However if your library only makes a single request at a time it might not utilize HTTP/2 to it's full potential as only a single HTTP/2 stream will be utilized then. In this case it might make sense to examine whether the library can be configured to load a number of parallel resources at once.