Skip to main content
blazy

bLazy.js – A lazyload image script

2016.05.09: New release, bLazy version 1.6.2

bLazy is a lightweight script for lazy loading and multi-serving images. It’s written in pure JavaScript why it doesn’t depend on 3rd-party libraries such as jQuery. bLazy works on all modern browsers, including on IE7+.

Contents

  1. How to use bLazy
  2. Options
  3. Public functions
  4. Responsive Images
  5. Iframes, videos, unity games etc.
  6. With AngularJS
  7. Changelog (github)
  8. License
  9. Support
  10. More lazyload examples (link)

How to use bLazy (lazy load images)

You can lazy load your images in just two easy steps.

Step 1) Change your image markup a bit.

  • Add class “b-lazy”.
  • Add a placeholder image to the image source (src). In my example I’m using a base64 encoded transparent gif so it won’t do any extra requests.
  • Save the real image source in the data-src attribute
    <img class="b-lazy" 
         src=data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
         data-src="image.jpg"
         alt="alt-text"
    />

Step 2) Include blazy.js and initialize it. If you’re using jQuery (or simliar) do it in document.ready:

    <script src="blazy.js"></script>
    <script>
        ;(function() {
            // Initialize
            var bLazy = new Blazy();
        })();
    </script>

bLazy comes with a few options

Options– key [type] (default value)
breakpoints[array] (false) Multi-serve images based on screen size. Go to multi-serve image example
container [string](window) If you want to lazy load elements inside a scrolling container change the default value to the selector of the container
error [function(ele, msg)] (false) Callback for when something goes wrong. There are two error messages, missing and invalid. You’ll get missing if no data-src is defined. Invalid if the data-src is invalid. Go to callback example
errorClass [string](‘b-error’) The classname an element will get if something goes wrong.
loadInvisible [bool](false) Set to true if you want to load invisible (hidden) elements.
offset [int] (100) The offset controls how early you want the elements to be loaded before they’re visible. Default is 100, so 100px before an element is visible it’ll start loading.
saveViewportOffsetDelay [int] (50) Delay for how often it should call the saveViewportOffset function on resize. Default is 50ms.
selector[string] (‘.b-lazy’) Element selector for elements that should lazy load. If you want to lazy load all images write ‘img’. You can add multiple selectors separated with comma; ‘.b-lazy, .bLazy, .blazy’.
separator [char](‘|’) Used if you want to pass retina images: data-src=”image.jpg|image@2x.jpg”. Go to the retina image example
src [string] (‘data-src’) Attribute where the original element source can be found
success [function(ele)] (false) Callback for when an image has loaded. Go to callback example
successClass [string](‘b-loaded’) The classname an element will get when loaded.
validateDelay [int](25) Delay for how often it should call the validate function on scroll/resize. Default is 25ms.

You pass the options as an object of key/value pairs:

    // Format
    var bLazy = new Blazy({ 
        key: value
      , key: value
      , key: value
    });

Selector

You can change the selector if you don’t want to add the ‘b-lazy’ class or if you need to have multiple.

    // Example
    var bLazy = new Blazy({ 
        selector: 'img' // all images
    });

Offset

The offset controls how early you want the elements to be loaded before they’re visible. Default is 100, so 100px before an element is visible it’ll start loading.

    // Example
    var bLazy = new Blazy({ 
        offset: 100 // Loads images 100px before they're visible
    });

Images inside a container

You can also lazy load images inside a scrolling container, just define the selector of the container:

    // Example
    var bLazy = new Blazy({ 
        container: '#scrolling-container' // Default is window
    });

Callback when image has loaded or fails

If you need to do anything when an image has loaded or fails you can pass a callback function:

    // Example
    var bLazy = new Blazy({ 
        success: function(ele){
            // Image has loaded
            // Do your business here
        }
      , error: function(ele, msg){
            if(msg === 'missing'){
                // Data-src is missing
            }
            else if(msg === 'invalid'){
                // Data-src is invalid
            }  
        }
    });

Retina images

If you’re not doing retina-first don’t worry. It’s easy to serve retina images for retina displays. Just add the source to the retina image in the data-src by using the separator (default is ‘|’) and bLazy will do the rest:

    <img class="b-lazy" 
         src=data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
         data-src="image.jpg|retina-image.jpg"
         alt="alt-text"
    />

Background images

You can also lazy load background images. If the element with the lazy load class (default: ‘.b-lazy’) isn’t an image, the source will be added to the element as a background image:

    <div class="b-lazy" data-src="background-image.jpg"></div>

Multi-serve images (obsolete)

Marked as obsolete in version 1.6.0. Instead I recommend using srcset and/or the picture element. See example 1.4 and 1.5 (http://dinbror.dk/blazy/examples/)

You can multi-serve images, so users on smaller devices will get a smaller image served and the page will load faster. If you have more than one it’s important that the widths are ascending like in my example; 420 comes before 768. If you set up a multi rule but your image markup doesn’t have the src attribute on it, it’ll look after the default src, data-src.

    // Example
    var bLazy = new Blazy({ 
        breakpoints: [{
	          width: 420 // max-width
		, src: 'data-src-small'
	     }
           , {
	          width: 768 // max-width
	        , src: 'data-src-medium'
	}]
    });

Image markup:

    <img class="b-lazy" 
         src=data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
         data-src="image.jpg"
         data-src-small="image-small.jpg"
         data-src-medium="image-medium.jpg"
         alt="alt-text"
    />

Image transitions

Image transitions are not a built-in feature in bLazy.js but you can easily add it with css. When an image has loaded a loaded class (default: b-loaded) is added to the image, so you can add:

    .b-lazy {
        -webkit-transition: opacity 500ms ease-in-out;
           -moz-transition: opacity 500ms ease-in-out;
             -o-transition: opacity 500ms ease-in-out;
                transition: opacity 500ms ease-in-out;
                 max-width: 100%;
                   opacity: 0;
    }
    .b-lazy.b-loaded {
                   opacity: 1;
    }

Public functions

Public functions
revalidate() Revalidates document for visible images. Useful if you add images with scripting or ajax
load(element(s), force) Forces the given element(s) to load if not collapsed. If you also want to load a collapsed/hidden elements you can add true as the second parameter.
You can pass a single element or a list of elements. Tested with getElementById, getElementsByClassName, querySelectorAll, querySelector and jQuery selector.
destroy() Unbind events and resets image array
    // Example
    var bLazy = new Blazy();
    bLazy.functionName(); // eg bLazy.revalidate();

Responsive images

An example on how to lazy load and multi-serve responsive images without having the page reflow.

Markup:

    <div class="image-wrapper ratio_16-9">
      <img class="b-lazy" 
        src=data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
        data-src="image.jpg"
        data-src-small="image-small.jpg"
        alt="alt-text"
      />
      <!-- Fallback for non JavaScript browsers -->
      <noscript><img src="image.jpg" alt="alt-text" /></noscript> 
    </div>

CSS:

    .image-wrapper {
        // Adding a loader and background color. The user will see it
	// if the image is loading slow.
        background: #1E1E1E url('loader.gif') center center no-repeat;
        width: 100%
    }
    .ratio_16-9 {
        // The image has a 16/9 ratio. Until the image has loaded
        // we need to reserve some space so the page won't reflow.
        // How to calculate the space (padding-bottom): 9/16*100 = 56.25
        // Another example: you have an image 400x250.
        // So if you want to calculate the space you do: 250/400*100 = 62.5
        padding-bottom: 56.25%; 
        height: 0;
    }
        .b-lazy {
            max-width: 100%;
        }

Iframes, unity games etc.

With blazy.js you can lazy load everything with a src attribute, not only images. For example iframes:

<iframe class="b-lazy" data-src="page.html" width="300" height="300">
 <p>Your browser does not support iframes.</p>
</iframe>

With AngularJS

Some users have asked if they can use blazy.js together with angular.js. The short answer is yes. Blazy.js is just plain javascript why you of course can do that. However since angular strippes the data-prefix from attribute names as part of the directive-name normalization process you either need to:

  • change the default data-src name because otherwise it’s like setting two src’s and firefox and chrome handles that differently.
  • or don’t have any default src.
// Example
var bLazy = new Blazy({ 
    src: 'data-blazy' // Default is data-src
});

//Markup
<img class="b-lazy"    
     src="placeholder-image.jpg"
     data-blazy="image.jpg"
     alt="alt-text"
/>

or

<img class="b-lazy" data-src="image.jpg" alt="alt-text" />

License

bLazy is licensed under MIT and the DWIWYWBPVMS license. (Do With It What You Want But Please Visit My Sponsor).

Support

Support bLazy by visiting my sponsor:

Related articles

147 thoughts on “bLazy.js – A lazyload image script

  1. Hi Dinbror,

    Thanks you very much for your script
    it’s great and very easy
    have a nice day
    Cyril

  2. Hi,

    This looks really useful. Have you tried the plugin with imazen slimmage? We really need the dynamic imageresizing capabillities of slimmage, but lazy load on top of that would be fantastic!

    Thanks
    Rune

    1. Hi Rune.

      Blazy support srcset and the picture element which is supported in all major browsers today. Otherwise there are polyfills for legacy browsers.

      Wouldn’t that solve your issue?

      Hygge
      Bjørn

    1. Hey Roman.

      It’s removed after image load to present the makeup as clean as possible. Do you need it after load?

  3. Hey,

    First think first, thank you so much for this amazing plugin.
    I use it on my website : http://www.jmbelloteau.com and the main functions work as expected so I’m happy.

    I just have to little problem and I can’t figure out the solution :

    – the load invisible function is not working
    – the css class for transition (b-lazy loaded) work only on desktop, not on mobile. (pictures just pop up without fading)

    Do you have an idea to resolve this two problems?

    Thank you so much.

    Cheers

      1. Hello Dinbror,

        Problem one: I activated the invisible function of your plugin but on the photo page of my website, the pictures don’t load if outside the viewport once the visible pictures are loaded.

        Problem two: If you go to my website, you will see that the css animation are working on the home page.
        But It’s didn’t work in the photo page. Maybe because the have 3 parents div?

        Thank you so much for your help

  4. Hi Dinbroh,

    I commented above but thought I’d start a new post.

    Awesome plugin and really easy to use however I’ve fallen in to the same trap a few others on this page have had with carousels. I’m using slick combined with blazy and it’s working perfectly until you drag or click to the thrid slide. https://jsfiddle.net/a4emf9qu/ If you scroll up or down or resize the browser it shows again but not onload.

    Do you know how I can solve it?

    Cheers and thanks again

  5. Thanks for this useful script/plugin, it works great.
    I noticed that the html doesn’t validate unless you encase the data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== in quotes –
    ie “data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==”.

  6. Great piece of work, absolutely no issue, just set and go and it works. Thank you.

  7. Hi, does your script support pixel density descriptors like 2x, 3x, 4x? And if not do you have any plans to implement it. Great script by the way.

    Regards

  8. Hi Dinbror

    Thanks for making this. The SEO considerations are vital and it’s real easy to setup.

    I have a gallery with lazy loaded images working (great!).

    I’m now looking at hiding my gallery until someone clicks a “view gallery” DIV. It’s pretty simple CSS and jQuery which works fine too.

    I notice the gallery DIV and content will load but the actual images fail to load.

    If I remove the hidden gallery and load the page “normally”, everything works as it’s supposed to and the blazy images load fine.

    My actual lazy script is very simple as follows:

    var bLazy = new Blazy();
    offset: 100;

    Is this something you’ve enountered before which I need to cater for?
    Many thanks
    P

    1. Blazy wont load or add hidden images to the load list.
      You can call the public function revalidate() after the view gallery button is pressed and it should work

      1. Thanks but I’m a little confused.
        Do I simply update the following

        var bLazy = new Blazy();
        offset: 100;

        to this
        var bLazy = new Blazy();
        offset: 100;
        bLazy.revalidate();

        or do I need to somehow bind that second script to my link of


  9. I don’t know what is wrong. I have created this gallery page using blazy load which works perfectly when I connect to internet with Alliance broadband, but only 2-3 images are loaded when I connect with Vodafone 3G.

    http://onedayintime.net/gallery_blazy.php

    It should not be a Vodafone network issue as it opens other pages quite good. It should not be a code issue as it opens perfectly with Alliance broadband. What else then!

    1. ummm.. okay there was a syntax error and somehow Alliance broadband was supplying cached images. I have corrected that and is working like charm. Thank you for the wonderful script.

  10. How do I get this working with Masonry? It works, but it messes with the layout of Masonry. Is there anything I need to do to make the images that load with b-lazy follow the Masonry layout?

    1. Do you have a live example, jsfiddle or similar?

      Its possible. I have been using them together

        1. You might have to call the public load or revalidate function. Do you have a live example? What carousel are you using?

  11. Great plugin but I can’t seem to get it to work properly with getmdl.io.

    The “visible” images loads… but when I scroll, the rest of the images of the page don’t load. They do load if I resize the window (change viewport).

    I’m using the very basic implementation, b-lazy class, script at the bottom, etc.

    Anybody encountered the same issue?

  12. Hi,

    Great script!

    I’m currently using the following in my WordPress theme to output a post’s thumbnail:
    ‘b-lazy img-responsive’ ) ); ?>

    And it outputs it as:

    I can’t seem to work out how to make it use data-src instead so it works. Any ideas?

    Thank you!

  13. Cool Plugin,

    responsive is not optimal. When i resize the page, i have the same image. only at reload i become the right image. Thats not good. Can you add this?

  14. When working with an templating engine (in my case pureJS) wrap the blazy JS init in a window.load instead of a document.ready function to get it working

  15. Thanks for this helpful plugin. I just about have it working as intended. The only issue is that my loading gif image isn’t showing. I have it specified as the src and I have checked the path. When I inspect the image, it shows the loading image as present in the code, but it never shows on the page. I tested on slow connections… nothing.

    Any thoughts?

  16. Hi,
    I was just thinking of using bLazy in my project but I can’t find the way to use srcset with it. Does this script support srcset?

    Thanks

  17. Blazy is awesome I’m using it in my site, I just have a question:
    I have a slideshow that works horizontally. Only the first four images in the slideshow are visible, showing the next images works by pushing a button.

    when I go to the slideshow, the first four images loaded well, but after pushing the next button, the next images are not loaded untill I scroll upwards or downwards.

    how this is solved??

    Thanks!

    1. Hey seily.

      You either need to call revalidate or load the next bunch of images in the slider with the public load method.
      Let me know if you need more help.

      1. Hi Dinbror,

        Love the plugin but I’m having problems loading images in a carousel also. I’m using slick but only the first two images are showing then the rest are hidden.

        I’m using this to initialize blazy –

        ;(function() {
        // Initialize
        var bLazy = new Blazy();
        bLazy.revalidate();
        })();

        Do I have to use bLazy.revalidate(); when I call slick?

        Cheers,
        Joiner

  18. Thank you Dinbror for sharing this useful script. It works like a charm and is really fast!

    I have a question regarding success triggering. Is it possible to create an event which triggers when all images in the viewport are loaded? Like the success function, but for all images that you see in the browser?

    I want to create a loading animation with a fix position on the bottom which always appears when blazy is loading elements. Is there a way to create it?

    Thank you in advance for your help

    Christoph

  19. Is it possible to ‘watch’ multiple containers? I have two scrolling image lists within containers and would like to lazy-load both of them. I thought I would initialize another variable, with a different container, but I see above that would create identical event listeners. Is there any way?

    1. Hey Bill.

      You can either use the same class for both containers or pass a comma separated string to the container option

  20. Incredibly simple, elegant, and powerful plugin.

    My hats off to your wonderful documentation also.

  21. Hello,
    i would like to use the b-laze in a slideshow in order to lazyload images in “li” tag (more than 50).
    But in order to turn the invisible images into visible with scrolling i would like to make them visible with next/previous buttons of the slideshow.

    To be more accurate i would like to:
    First and second images loads when site load, third image loads when user hit next button (from first image), forth images loads when user clicks next to go in the third…etc.

    I would like to work like this because the loading time of the site is really huge.
    Is it possible?

  22. Hi,

    Good job !
    Just an error in this sample : <div class="b-lazy" data-src="background-image.jpg"

    The first tag in not closed 🙂

    1. Thanks Francis.

      I’m using a custom one:
      .code-undefined{color:#617A61}
      .code-string{color:#FA8072}
      .code-function{color:#FFA54F}
      .code-int{color:#2B91AF}
      .code-comment{color:#7CCD60}

  23. Holy shills this plugin is amazing, it’s wonderful, works fast and loads so beautifully. I’m using it with background images and I’m in awe. Thanks for taking the time to do such an amazing work.

  24. Firstly: thanks for this great plugin. it’s small, no dependency and easy to use. Just what you expect from a javascript plugin.

    And now. I’ve also had the issue where “visible images” were not always loading on page load. And not even after starting scrolling up and down.

    All I did was to wrap the blazy function into:
    window.onload = function() {
    ;(function() {
    // Initialize
    var bLazy = new Blazy();
    })();
    };
    And that solved the issue on my side.

    I’m not a js guru, but using $(window).load(function() or other jQuery way to load such as $(document).ready(function() might not be the correct approach since blazy is not a jquery plugin. You may as well leave it alone from jQuery.
    I’m not saying it won’t work, but it’s always better to use a script as it was intended.

    I hope it helps.

  25. Is there a way to wrap this into a angular directive?can you give example on how to implement this inside a directive?

      1. I want to use it in angular, It’s working fine when I load static image, but when I try with dynamic image url like data-src=”{{mydata.image}}” or ng-src=”{{mydata.image}}” it’s says invalid so can you tell me how can I fix it?

  26. Dear Bjørn,

    thank you so much for the amazing plugin, there is some quality code in there, and also for taking time to give feedback to all this people.

    I’m using blazy to serve responsive images, my breakpoints are 375px and 480px.
    On iOS devices, when I change orientation portrait-landscape I go from one breakpoint to another and ideally I should load 2 different images, but since the plugin uses device width the loaded image is always the same, no matter the orientation.

    Is there a quick way to override this and use window width to load the images?

    Thank you for your time.

    Pavel

    1. You will need to remove the part that normalize the markup (line 176) and then implement the changing breakpoint logic. I would do it with window.matchmedia depending on the browsersupport.

      Let me know if you need more help

  27. Hi!

    I really like this plugin, but I’ve noticed that breakpoints doesn’t working.
    I’ve try this with IMG and DIV and it’s doesn’t work at all.

    Even Your demo isn’t working properly :/

    1. Hey Igor.

      Can you elaborate? What it not working?
      The breakpoints are defined by the device width not the browser width. It means that it’ll look at your screen width which won’t change when you resize your browser window.
      The reason why I’m looking at the device width and not the width is that I don’t want to load multiple image sources for the same image when you resize (multiple server request per image). And if you have a big screen but the start width of your browser window is something small I don’t want to upscale a low res image if you resize it up.

  28. Hi,

    I’ve got an art gallery website and it works perfectly, its an combination with Angular and Masonry. Except for one detail.

    I’ve got multiple filters that removes the current array in the masonry, it then loads in a new array and the masonry effect is reloaded.

    After that, all my images from the array are loaded, but invisible. The public bLazy function that I call upon, with or without a timeOut aren’t working.

    Any ideas?

  29. FINALLY a respectable and very good lazy loader script. I’ve tried several out there and all are terrible. Yours is the only one of quality workmanship. Had to post to show my appreciation. And bravo for explaining all the options and giving examples.

  30. Is tahere any function like in ajax beforeSending?
    I would like to make a loding screen why the images is loading.

  31. Thank you for this code. This is excellent. Being able to lazy load css background images and multi-serve images for small screens is super useful.

    Couple issues I noticed:

    1) Multi-serving image seems to only look for the actual device width and doesn’t look for device orientation, so I can’t serve different images depending on if iPad is in portrait or landscape view. I suppose I should stick to images of same proportion to avoid the issue, but sometime I do want to serve totally different images when a layout changes completely.

    2) On Chrome I noticed that if I scroll down to where an image is lazy loaded, and then reload the page, sometimes the image doesn’t load. Not sure why that is, because it’s not doing that for your demo page…

    Looking forward to your updates!

  32. When I am using b-lazy with imagesLoaded js plugin along with masonry, it doesn’t load images and only load images when I scroll the window.

    $container.imagesLoaded(function(){
    $(‘.gallery-wrap’).masonry({
    columnWidth: “.grid-sizer”,
    itemSelector: ‘.gallery-wrap .item’
    });
    });

    b-lazy after this code doesn’t print on page refresh, but you need to scroll to print them. Above this code everything works fine.

  33. Hi,

    When I scrolled down below my page and refresh the page, it will reloads the image to the position that I had scrolled down earlier,

    I want to press the refresh, it will not reload the image that returns the first position, the handle configuration or how,

    Thanks for any help,

  34. Hello Bjørn,

    Your script works fine, but I have one question.
    I’m using an image slider where all the images are positioned horizontally next to each other. Only the first image in the slider is visible Showing the next image works by pushing a button (javascript event).

    If I scroll to the slider, the first image is loaded perfectly, but after pushing the next button, the next image is not loaded untill I scroll upwards or downwards a little (guess that triggers it).

    any idea how to solve this?

    Thanks!
    Serge

  35. Hi Dinbror,
    Been using your blazy script for a while – but just venturing into using the multi-serve feature.
    I’ve put together a couple of tests on JSFiddle for my own sanity as I’ve not been getting the results I expect on an iPhone.
    This is my initial setup:
    https://jsfiddle.net/floqdesign/6fynzsjx/
    With multiple breakpoints and the current version of blazy being loaded.
    The issues
    When testing this fiddle on my iPhone I wasn’t getting served the medium image when the phone was landscape as I expected with a 480px breakpoint being defined.
    I was getting the small image for both orientations.
    I looked at your script and did some tests in the console and found that the query you use `window.screen.width` only ever gives the width of the iPhone – regardless of orientation.
    My second setup example:
    https://jsfiddle.net/floqdesign/tyn1s8gm/
    This is a cut-down version with only 2 breakpoints defined.
    I’ve included the blazy.js inline as I’ve modified line 69/70 from `window.screen.width` to `screen.outerWidth` which does differ on the iPhone when in landscape or portrait mode.
    Perhaps I’m missing something about using `screen.outerWidth`?
    I found this article:
    http://www.quirksmode.org/blog/archives/2012/03/windowouterwidt.html
    .. but it’s 3 years out of date.
    My tests in the latest versions of Chrome, Firefox, Safari and IE all work.
    Taking IE back to v8 doesn’t work but there is a solution:
    http://stackoverflow.com/questions/5954725/the-script-does-not-work-in-ie-how-can-i-fix-it
    When I say my tests all ‘work’, OK they don’t all return the same value – some browsers were taking some of their chrome or scrollbars into consideration – but they’re still returning a usable true screen width value.
    Not able to test on other mobile devices to test.
    Your thoughts?

  36. Hey there,

    This is a great script to use in place of Foundations Interchange function, which does not allow for lazy loading.

    However, I am having the similar issue where sometimes, not images in view load at all. I can’t get this to consistently happen, but I’ve seen it in both Safari and Chrome.

    This is the page where the in-view images aren’t always loading: http://www.dearcastandcrew.com

    Thanks for any help (and a great script)!

  37. Hello

    Great Plugin!

    would like to know possible using multi data-src and serve between jpeg and webp images if browser support webp.
    data-src=”myimage.jpg” data-webp=”myimage.webp”

  38. Hi,
    I used the script like in your demo but something strange is happening for me – The images are already loaded when the page opens.

    My markup is like this
    <a href="”><img src=data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== data-src="” class=”b-lazy img-responsive” alt=”slider-thumb” />

    and js

    jQuery(document).ready(function ($) {
    “use strict”;
    var bLazy = new Blazy({
    breakpoints: [{
    width: 320 // Max-width
    , src: ‘data-src-small’
    }]
    , success: function(element){
    setTimeout(function(){
    // We want to remove the loader gif now.
    // First we find the parent container
    // then we remove the “loading” class which holds the loader image
    var parent = element.parentNode;
    console.log(‘loaded already’);
    parent.className = parent.className.replace(/\bloading\b/,”);
    }, 200);
    }
    });

    Any ideeas ?
    Thanks

  39. Hé Bjørn,
    Thanks for the great script. I seem to have a problem with lazy loading images that are part of an google images like script.

    It’s an overview of images and when I click on one of them, a div receives ‘display: block;’ and it toggles open. Part of the toggled open div is a bigger image that I would like to have lazy loaded also… but instead it doesn’t do anything.

    I tried to give both images the class ” but that didn’t work. I tried giving them seperate classes and added ‘selector: ‘.b-lazy,.b-lazybig” to the call. But that didn’t work either.

    I’m afraid it has something to do with the toggled div…

    any ideas?

    Thanks!
    Keston

  40. The issue others have mentioned where images that begin in the viewport (or within the offset) do not load is happening to me. Works ok in OS X Chrome, but in Safari those images never load, making this script unusable. It’s unfortunate, I had my whole site set-up to use this and it was working well, but the Safari issue is forcing me to switch to something else.

    Also, I really think the script should look at the viewport width instead of the screen width. I have instances where my responsive images change proportion based on viewport width, and if someone loads a smaller window on a larger screen, it creates some real issues.

  41. Hi great plugin but I’ve got a problem. In some pages (apparently random) blazy doesn’t trigger and images don’t load. No error messages.. Any idea?

  42. Hi,

    Great plugin. Is there a feature to unload images as well once they are no longer in the viewport?

    Cheers
    J

  43. Hey Bjørn

    Awesome script! Keep up the great work…

    Just want to tell you there’s an even shorter version of the base64 decoded GIF.

    You use:
    R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==

    Smaller (26 bytes):
    R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=

    Using it for some time without problems.

    Source (in the comments):

    Got a question/request. Would it be possible to lazyload several files in one go, for the background of an element, which can have multiple backgrounds. Just like:

    data-src="image.jpg|retina-image.jpg"

    but where you can force a load of all the files with a switch or using another symbol instead of the pipe.

    Regards
    From DK 🙂

  44. Hey, cool plugin!

    Does it destroy images that are scrolled out of the viewport? Is it possible to destroy images loaded via background-image?

  45. Is it possible to use the Blazy also like an “inview” plugin, so that it could add a class to some specified div? I have css multiple backgrounds and I cannot find a way to lazy load some parts of them without enlarging html trees.

  46. Hello

    I use javascript for my application and my question is.
    if the callback get success, can i save the image on my system?
    where i find this image the blazy is loading ?

    thanks for your help

  47. Hi Bjørn,
    I’m experiencing an issue with IOS (iPhone iPad)
    My first image doesn’t appear until I scroll…
    I’d like to get it loaded on $(document).ready

    I guess I can achieve this by using the .load function but nothing seems to work on IOS

  48. Hello

    Is there a way to set the retina image source in the code where blazy is initiated?
    We would like to keep the img tag not so clustered.

    My suggestion would be to add an attribute in the breakpoint definitions “src-retina”, where we can set a data source.


    // Example
    var bLazy = new Blazy({
    breakpoints: [{
    width: 420 // max-width
    , src: 'data-src-small'
    , src-retina: 'data-src-medium'
    }
    , {
    width: 768 // max-width
    , src: 'data-src-medium'
    , src-retina: 'data-src-large'
    }]
    });

    What do you think?

    Cheers,
    Aldo

    1. Why not go with a retina-first approach and always downscale.

      In this way you don’t need multiple images per breakpoint and all new devices has retina screens 😉

      1. This means I would still have to go with this:

        data-src="image.jpg|retina-image.jpg"

        Or how would the code look like?

    1. Hey Seppo.

      That’s how it should work. How should it know that you’re adding an already loaded image with ajax? But the good thing is that the image is cached and will load/show instantly.

      Cheers
      Bjørn

  49. My example code was stripped away, but it was just {span class=”b_lazy” data-src=”/images/image1.jpg”}{/span}

  50. In the new patch of posts there isn’t “b-loaded” class by default, even if it’s the same avatar that was already loaded in previous patch. If first Ajax response is like and second response is the same then in the second response it will handle data-src, because there isn’t loaded class yet. It may be that this is uncorrectable problem and we just have to live with this.

  51. There’s a little problem when loading more content via Ajax. Didn’t confirm this yet, but I think that after calling revalidate() -function b-lazy forgets previously loaded images and will request same images again. This is a problem when there’s same avatar -images in the new patch of posts, for example.

    1. Hey Seppo.

      If you confirm, please post a live example. Works fine here. The code won’t load an image if it already has the loadedclass

  52. Thanks. Cool tool. I’ve defined a breakpoint, but I’ve only provided a “data-src-small” for my extra large, non-essential background image. My other images only have a “data-src” defined. When I view with small viewpoints, it seems like the other images are displayed as normal. This is behaviour I wanted. I just want to check it was also the behaviour you expected.

  53. Hey there – great plugin!

    Is it possible to load the image dimensions before the actual images? When I scroll through a load of images they jump around a bit as the actual image dimensions are loaded.

    Thanks!

  54. Hi Bjorn,
    Impressed with your nice work, thanks 🙂

    I just found a strange bug with it:

    I have a large enough list of images and they are out of initial page view.
    On page scrolling down everythin’s OK, images are loaded.

    BUT if to reload page being among those images – they don’t load at all. Scrolling down or up loads invisible images, but those initially in view – remain unloaded.

    btw this bug could be reproduced on FF only (chrome does it OK).
    FF v.29 I have.

    Regards
    Iho

    1. Hey Iho – I’ve had similar problems in Chrome with a site I’m developing now. I can’t replicate on the bLazy demo page, however.

      My temporary (horrible) workaround is to trigger a revalidate after 500ms, which seems to do the trick. Simply triggering the revalidate without the setTimeout doesn’t cut it unfortunately.

      setTimeout(function(){
      bLazy.revalidate();
      }, 500);

      1. Same issue here, did you find a solution? For me in Chrome only sometimes blazy doesn’t trigger, in particular on page reload. Any idea?

        1. Hi there,
          had the same issue with chrome and safari. Running blazy on
          $(window).load
          instead of
          $(document).ready
          solved the problem here.
          Cheers,
          tom

          1. Hey guys.

            Do you have live examples? It smells like repainting issues. You need to reserve the space the images uses like I do on my demo page.

  55. Hello 🙂
    your code works great, however, with the jquery mobile filterable widget input, the ‘data-src’ image do not display because you might have call for an image which have not been ‘blazy’ parsed yet, I guess there is some work on this particular point since we have to consider that this plugin exists for huge list of images.. and because the filterable widget when using jquerymobile is ‘quasi’ mandatory.
    Anyway
    Keep on the good job !

    1. Hey Piem.

      Have you tried to use one of the public functions, revalidate() or load(element)?

  56. Thanks for the awesome plugin!

    I’m using Parallax-ImageScroll on a prelaunch local site, and I think that the blazy monitoring of scroll position is causing the parallax to lag on aggressive scrolling… Is there a way to destroy blazy when all images have loaded successfully?

    tx again! Tim

  57. Thanks for this great script!

    Can you help me with follow questions

    1) I use the script on a page that has collapsible tabs (display none->block) – what is the best way to re-run bLazy.js again to load newly visible images?

    2) What is the best way to handle errors? Replace 1×1.gif with default image via javascript (can bLazy.js do this and how?) or assign a default background image to “b-error” class?

    Thanks and have a nice day!

    1. Hey Robert.

      1) It depends on the use case. There are two ways. Either call revalidate which validates the document again or trigger the newly added item(s) with the .load() method:

      var bLazy = new Blazy();
      bLazy.functionName(); //bLazy.revalidate(); or bLazy.load(element);

      2) I normally hide the image or show a default error image. If it’s an image you can do it in the error callback (http://dinbror.dk/blog/blazy/#Callback) like this:


      var bLazy = new Blazy({
      error: function(ele, msg){
      ele.src = 'error-image.jpg'
      }
      });

      Or if it’s a background image add the image in css to the “b-error” class as you write.

  58. I’m currently toying with the idea of combining Nested.js with element background images loaded with bLazy – but currently the bLazy makes the elements disappear after loading.

    I traced the problem to the line 147, where the background image is inserted with setAttribute(‘style’). Nested.js also plays with style attributes but those changes get overwritten when the background image is set.

    If bLazy changed only the background image this problem could be avoided – for example something like:


    ele.nodeName.toLowerCase() === 'img' ? ele.src = src : ele.style.backgroundImage = 'url("' + src + '")';

    1. Hey Saku.

      Thanks for your feedback. I’ll update the script soonish 🙂
      You’re right, I only need to change the bg img.

      Thanks
      Bjørn

  59. Great plug! Only one issue: It does not detect divides that are wrapped in a li tag. Any ideas? Thanx.

    1. Hey Jason.

      That sounds odd. Do you have a live example or codepen/jsbin/jsfiddle I can see?

      Cheers
      Bjørn

      1. Hi again. To move on, I rewrote the HTML mark-up for this particular use to use an . In doing so, I discovered another issue where the images will not load if the view-port is smaller that 1298px. I posted a question over on StackOverflow. You can get the link to inspect the site over there. Thanx for your help.

  60. This works great! I was able to test it with the multi serving images using Chrome emulator. Just wondering if I can make it work with image container width rather than the screen size width? The reason is that on the page, the column used for displaying the images might not occupy the max screen size width.

    Thanks very much in advance.

    1. Hi Markus.

      That’s a really good question but unfortunately a grey zone.
      I have not received the “Image Mismatch” message for any of the sites I use bLazy on.
      The google bot also understands/executes basic JavaScript but if it’s important that your images are indexed in google images I wouldn’t lazy load them.

  61. Hello

    Great Plugin!

    I try to multi-serve responsive images with breakpoints. Did it all like in you example.
    Unfortunately it always loads the image defined in data-src and not the corresponding ones defined for each breakpoint.

    Any idea?

    Thanks,
    Aldo

    1. Hey Aldo.

      How do you test it?
      The breakpoints are defined by the device width not the width. It means that it’ll look at your screen width which don’t change when you resize your browser window. You can emulate device widths in chrome: https://developers.google.com/chrome-developer-tools/docs/mobile-emulation#enable-emulation-panel.

      The reason why I’m looking at the device width and not the width is that I don’t want to load multiple image sources for the same image when you resize (multiple server request per image). And if you have a big screen but the start width of your browser window is something small I don’t want to upscale a low res image if you resize it up.

      Hope it make sense 🙂
      Bjørn

      1. Is there anyway to override this behaviour ?

        For example i am in mobile portrait view.. Now width is less than 492 and is use a image. And if the user turns his phone to landscape view and now the width is more than 492 and I would want to load another image.

        How to handle this scenario.

  62. Hi, I am trying to use this with multiple selectors. I have two different instances of the plugin and it doesn’t seem to work.
    var bLazy = new Blazy({
    selector: ‘.lazy’,
    });
    var ILazy = new Blazy({
    selector: ‘img’, // all images
    src: ‘data-orig-file’
    });

  63. Hi.

    This is a cool plugin so well done.

    I was wondering if you had any working example or codepens of the ability to multi-serve responsive images because I can’t quite get it working.

    Thanks for you help

    Alan

  64. Hi thanks for the great plugin, i am trying to add Blazy to slider but i alwys get this error in firebug :
    TypeError: dataSrc is null
    var dataSrcSplitted = dataSrc.split(options.separator);

    would you help on this, thanks Again 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *


Warning: Parameter 1 to W3_Plugin_TotalCache::ob_callback() expected to be a reference, value given in /var/www/dinbror.dk/public_html/blog/wp-includes/functions.php on line 3549