It may not be obvious to everybody, but everything that relies on the use of the
src attribute can be “lazy loaded”.
Now, what most people do is defer the loading of images: you take your
img tags, strip them of their
src attributes, and store the value somewhere else, like a
data-src attribute. This way, the browser won’t load the resource (image, in this case) at all.
When you do need to load the image, simply convert the
data-src attribute to an a
src attribute with the same value, and the browser will start loading the resource instantly.
var image = document.querySelector( "img" ); image.setAttribute( "src", image.getAttribute( "data-src" ) );
Recently, I was working on a project that required a lot of embeds to be present in page, with more of them optionally loaded upon clicking on a pagination element.
Embeds can be heavy. No, heavy is not quite the word I’m looking for. Lots of embeds can kill a web page performance. But, again, I had no other choice but to have a bunch of
iframes together side-by-side.
Then it dawned on me: the same reasoning that we use for images could be applied to those
iframes as well. As a matter of fact, whatever relies on a
src attribute, even stylesheets, can be lazy loaded like that.
And that’s exactly what I ended up doing: having a bunch of inert
iframes, each one with its
data-src attribute regularly filled, waiting to be converted to the standard
Sure, if you load a lot of those i
frames, you’ll end up having a pretty resource-demanding page at the end, but sure enough, the initial load will be much much lighter.