Lazy-loading resources into HTML modals

I don't usually write about web technologies, since I have to search literally everything I do (although I gather this is what most of you web-devs do!). But today, I figured out something on my own, for which I couldn't find a solution on stackoverflow 👊.

The problem is simple. If you visit my homepage, you'll see that I have quite a few projects listed - and I plan to have many more in the future 😎! Each of these projects has, on average, 4 screenshots. Since the details of these projects are shown in modals, I thought it would be elegant to lazily load the images (and videos etc) required inside. I was pretty upset when I couldn't find an easy way to do this. I tried using this library, but couldn't wrestle it into what I wanted. Plus, I'm not a huge fan of using libraries for tasks I think should only take a few lines of code 😔.

Is nothing easy?

So i gave it a crack, and this is what I came up with:

$(function() {
    $('.portfolio-modal').on("show.bs.modal", function(){
        $(this).find(".lazy").each(function() {
            $(this).attr('src', $(this).attr('data-src-lazy'));
        });
    });
});

Then, for all my images (and things like iframes as well), instead of providing a src attribute, I provide a data-src-lazy attribute instead. This way, when the modal is opened, the code snippet will inject the src in and load the images. Hooray!

Don't ask me what happens when someone doesn't have javascript. It's not too difficult to think of a solution for that, and I'm not too bothered about those guys 😛.

I'd love to hear your thoughts 😊


© Krishan Patel 2015.