Giter Site home page Giter Site logo

dinbror / blazy Goto Github PK

View Code? Open in Web Editor NEW
2.6K 65.0 357.0 191 KB

Hey, be lazy! bLazy.JS is a lightweight pure JavaScript script for lazy loading and multi-serving images. It's working in all modern browsers including IE7+.

Home Page: http://dinbror.dk/blazy

License: MIT License

JavaScript 54.23% HTML 45.77%

blazy's Introduction

#hey, be lazy Downloads Latest Stable Version License

bLazy is a lightweight script for lazy loading and multi-serving images, iframes, videos and more (less than 1.4KB minified and gzipped). It’s written in pure JavaScript why it doesn’t depend on 3rd-party libraries such as jQuery. It lets you lazy load and multi-serve your images so you can save bandwidth and server requests. The user will have faster load times and save data usage if he/she doesn't browse the whole page.

Table of Contents

  1. Demo
  2. Usage & API
  3. Why be lazy?
  4. Changelog
  5. License

DEMO

http://dinbror.dk/blazy/

More examples: http://dinbror.dk/blazy/examples/

Codepen playground: http://codepen.io/dinbror/pen/HzCAJ

USAGE & API

http://dinbror.dk/blog/blazy/

INSTALL

You can install blazy.js with npm:

npm install blazy --save

or bower:

bower install blazy --save

CDN

If you don't want to host the script yourself you can link to the latest minified file:
//cdn.jsdelivr.net/blazy/latest/blazy.min.js on jsDelivr. Exchange latest with the specific version number if you want to lock it in.

WHY BE LAZY?

  • bLazy is used on big sites with millions of monthly visitors so it has been tested out in the real world.
  • bLazy is written in pure JavaScript why it doesn’t depend on 3rd-party libraries such as jQuery.
  • bLazy is lightweight, less than 1.4KB and less than 1.25KB if you don't need IE7- support.
  • bLazy is very fast. It has focus on performance why it also auto-destroys when it's done lazy loading.
  • bLazy can lazy load all types of images including background images.
  • bLazy is future-proof. It supports srcset and the picture element.
  • bLazy can serve retina images on retina devices.
  • bLazy can lazy load everything with a src like iframes, HTML5 videos, scripts, unity games etc.
  • bLazy supports all browsers used today including legacy browsers like IE7 and 8.
  • bLazy supports all main module formats like AMD, CommonJS and globals.

WISHLIST/NEW FEATURES REQUESTED BY YOU

  • Only preload "first frame" of progressive jpegs.
  • Add support for CSS background property; image-set (caniuse).
  • Add a class when the lazyloading begins.
  • Option to keen load once on screen images have loaded.
  • Add option to disable success/error classes
  • Animate the container that contains the image you lazy load. You can do that today by adding/removing a class in the success callback.

CHANGELOG

v 1.8.2 (2016/10/25)

  • Added null check in public load function.
  • Bugfix: Fixed this issue defaulting to window when passing revalidate or destroy in setTimeout as reference #73 and #112. Thanks PeteDuncanson.
  • Bugfix: If parts of container is outside window use the viewport boundaries #113 and #114. Thanks dbirkbeck.

v 1.8.1 (2016/10/22)

  • Bugfix: Created polyfill and check for support of Element.closest which was introduced in the container fix in v. 1.8.0.

v 1.8.0 (2016/10/16)

  • Bugfix: Non-visible images being loaded inside container #23 and #96.

v 1.7.1 (2016/10/14)

  • Bugfix: In safari the picture element always loaded the default/fallback image #92.

v 1.7.0 (2016/10/10)

  • Bugfix: When lazyloading picture elements it also loaded the fallback/regular image #92 and 108. Thanks @idoshamun
  • Refactored loadElement function to avoid redundancy.

v 1.6.4 (2016/10/08)

  • Bugfix: When lazyloading srcset images it also loaded the fallback/regular image #99. Thanks @m0uH

v 1.6.3 (2016/09/30)

  • Changed event listener to passive listener #106. Thanks @idoshamun
  • Added support for web components (shadow dom) #107. Thanks again @idoshamun

v 1.6.2 (2016/05/09)

  • Fixed bug introduced in v.1.6.0, not using retina/breakpoint src #90.

v 1.6.1 (2016/05/02)

  • Implemented a workaround for onload/onerror bug introduced in chrome v50, LINK. Fixed #85.

v 1.6.0 (2016/04/30)

  • Added support for srcset and the picture element. Fixed #69, #75, #77 and #82.
  • Added support for lazy load of videos with sources. Fixed #81.
  • Bugfix. Ensuring that error and success classes won't be added multiple times. Fixed #84.
  • Marked breakpoints as obsolete. Will be removed in upcoming version. Use srcset and/or the picture element instead.

v 1.5.4 (2016/03/06)

  • Fixed two Safari bugs: #66 and #78. Ensuring "DOM ready".

v 1.5.3 (2016/03/01)

  • Implemented #30. Keeping data source until success.
  • Fixed #47. After implementing #30 you can now get the image src and more information in the error/success callbacks.
  • Added example page to repo /example/index.html.

v 1.5.2 (2015/12/01)

  • Fixed minor bug where the error class was added when calling revalidate().
  • Minor refactoring

v 1.5.1 (2015/11/14)

  • Fixed toArray function so it now works in IE7 + 8 again. Bug introduced in 1.4.0. Thanks for reporting @imcotton.
  • Fixed #41. Added options for validate and saveViewportOffset delay.

v 1.5.0 (2015/10/30)

  • Added new feature. Now you can lazy load everything with a src attribute like iframes, unity games etc.
  • Fixed #45. Now you can pass an option if you always want to load invisible images/elements.
  • Fixed #49. Expanded the load function so it's now possible to pass a list of elements instead of only one element. Tested with getElementById, getElementsByClassName, querySelectorAll, querySelector and jQuery selector.
  • Fixed #63.

v 1.4.1 (2015/10/12)

  • Fixed #60. An "Uncaught TypeError" when options is null introduced in the refactoring in version 1.4.0.

v 1.4.0 (2015/09/28)

  • Fixed #56. Now it's possible to create multiple versions of blazy without overriding options.

v 1.3.1 (2015/02/01)

  • Added support for CommonJS-like environments that support module.exports like node.

v 1.3.0 (2015/01/23)

  • Fixed #34. Expanded public load function with force attribute, so you can force hidden images to be loaded.
  • Fixed #24, #32 and #35. Updated "elementInView" function with intersection check. Thanks @teohhanhui.

v 1.2.2 (2014/05/04)

  • Fixed #15, when you resize the browser window in another tab bLazy didn't trigger new images in view. Thanks joshribakoff.

v 1.2.1 (2014/03/23)

  • When lazy loading background images it now only updates the background-image css attribute. Thanks Saku.

v 1.2.0 (2014/02/15)

  • Important note: renamed option multi to breakpoints because it's much more descriptive.
  • Added AMD support.
  • Minor refactoring.

v 1.1.3 (2014/01/21)

  • Fixed hardcoded retina check (isRetina = true).
  • Fixed "Uncaught TypeError" when data-src is null. Instead it'll trigger the error callback.

v 1.1.2 (2014/01/03)

  • New feature: After many requests I added the possibility to handle retina images (if you’re not doing retina-first).
  • New feature: Now you can also lazy load background images.
  • Added new option, separator. Used if you want to pass retina images, default separator is ‘|’. (data-src=“image.jpg|[email protected]”).

v 1.1.1 (2013/12/27)

  • Fixed #1, resize/scroll events may be detached when adding elements by ajax.
  • Added new option, errorClass. Classname an image will get if something goes wrong, default is ‘b-error’.
  • Renamed option loadedClass to successClass so naming is aligned. Default is still ‘b-loaded’.

v 1.1.0 (2013/11/22)

  • Renamed success callback from onLoaded to success.
  • Added onerror callback; error.
  • Added the possibility to pass multiple containers instead of one.

v 1.0.5 (2013/10/7)

  • Fixed "Uncaught TypeError" when container isn't default (window).

v 1.0.4 (2013/8/29)

  • Added null check so we won't try to load an image if it's missing a data source.

v 1.0.3 (2013/8/27)

  • Added new option, loadedClass. Classname an image will get when loaded.
  • Added support for horizontal lazy loading.
  • Reduced throttle time for validate.

v 1.0.2 (2013/8/7)

  • Fixed typo in unbindEvent function.
  • Added support for IE7 as promised (fallback for querySelectorAll).

v 1.0.1 (2013/8/6)

  • Performance improvements.
  • Added throttle function to ensure that we don't call resize/scroll functions too often.
  • Cleaning image markup when image has loaded.

##LICENSE: Copyright (c) 2013-16 Bjørn Klinggaard. Licensed under the The MIT License (MIT).

blazy's People

Contributors

dinbror avatar m0uh avatar peteduncanson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

blazy's Issues

In Safari OSX offset option does not load images in view port after page load

I have a problem when using Safari/OSX and the offset option: The images in the view port do not get loaded on document.ready.
In my case I used offset: 200 and while the images in the view port appear on my Desktop PC using Chrome, IE or Firefox, they do not appear on my MBP Retina using the latest Safari browser. Only after scrolling up and down and having loaded all the other images, they appear.
I called the plugin like this:
jQuery(document).ready(function() {
var bLazy = new Blazy({
selector: '.thumbnail',
offset: 200
});
});

Add Bower support

Can you add bower support and tags? Currently we can only pull head.

Thanks!

Setting event listeners on custom elements

I running into an issue where the main content wrapper of a page has 'Momentum scrolling' style behaviour.

.wrapper {
    overflow-y: scroll; 
    -webkit-overflow-scrolling: touch;
}

This renders the window scroll listener useless as it will never fire. We now need to listen on the element with the wrapper class.

Could we have an option which let's us set the element to listen on (with a default of window)?

B-Lazy doesn't fire sometimes when page has been visited

Not sure what it happening, but in Chrome (35.0.1916.114) on a Mac OSX (10.9.2), visiting my site that I've already visited, and possibly cached, none of the b-lazy elements change, nor do the success or error events fire.

If I press refresh, everything runs normally. If I go up to the location bar and press enter it will load fine too. Just sometimes when opening a new tab and typing in the url and hitting enter.

Wondering if anyone else is experiencing this, and/or it is a b-lazy issue, or something else.

FYI, here is my call to b-lazy:

var bLazy = new Blazy({ 
    selector: '.b-lazy',
    offset: 180, // Loads images 180px before they're visible
    success: function(ele){
        // Image has loaded
        // Do your business here
        console.log('img loaded');
    },
    error: function(ele, msg){
        console.log('b-lazy error:' + msg);
        console.log(ele);
        if(msg === 'missing'){
            // Data-src is missing

        }
        else if(msg === 'invalid'){
            // Data-src is invalid
        }
    }
});

Here is where I'm experiencing the issue: http://staging.aspirebeverages.com (even clicking on this link for me is a case when it sometimes does not fire)

Any ideas? Thanks in advance!

Error with bLazy 1.4 an jQuery

Hi,

When I try to implement bLazy 1.4, I get the following error:

TypeError: undefined is not an object (evaluating 'a.error')
(anonymous function)blazy.min.js:5:2314
(anonymous function)localhost:1:40400
cjquery-1.11.1.min.js:3:28654
fireWithjquery-1.11.1.min.js:4:1939
readyjquery-1.11.1.min.js:4:3794
sjquery-1.11.1.min.js:2:30257

bLazy 1.3.1 still works fine, so I'm wondering if there is some way to tweak teh script to resolve this error.

Thanks for any help!

google chrome on android 4.3

Hi,

I'm implementing Blazy on a wordpress theme and everything works fine until we tested on Android 4.3 - Chrome. The image loading is not firing when you scroll.

Same implementation works fine on IOS Safari on iphone, and on same android but the default browser.

Is it something i can do or do you know a fix ?
thanks

Problem with detecting if element is inView

On my website I have been experiencing a problem with the script where it doesn't detect correctly whether an element is in view or not. It's because some images on my website ( bredymer.dk/biler.aspx ) return ele.getBoundingClientRect().left value less than zero meaning that their left coordinate starts outside viewport. This has caused some of the images not to load and I fixed it by

I have fixed it by modifying

    function elementInView(ele) {
        var rect = ele.getBoundingClientRect();
        var bottomline = winHeight + options.offset;

        return (
         // inside horizontal view
         rect.left >= -20
         && rect.right <= winWidth + options.offset  
         && (
         // from top to bottom
         rect.top  >= 0
         && rect.top  <= bottomline
         // from bottom to top
         || rect.bottom <= bottomline
            && rect.bottom >= 0 - options.offset
            )
        );

        return inView;
     }

where I set rect.left >= -20 . This is not a universal solution and only helped fixed problem in my website. Perhaps there are some universal ways to solve it?

add CDN info

GitHub.com is freaking out all day; I"m trying to add this to your README under ## API

### CDN

`//cdn.jsdelivr.net/blazy/latest/mainfile` to link to the latest minified file on [jsDelivr](http://www.jsdelivr.com/#!blazy).
Exchange `latest` with the specific version number if you want to lock it in.

I'll try to remember to get back to this later if you don't first.
Enjoy!

.load() doesn't work.

Looks like the code the .load() function references is faulty. "loadImage()" simply doesn't work. At all. It's also unclear whether you pass it a jQuery object or a native DOM element. I've tried both, doesn't work with either.

Add option to disable success/error classes

I'd really like it if I could disable the addition of success/error CSS classes. I handle all of the logic within the error handlers, so it's redundant and fills the markup with unneeded classes (not to mention the fact that it sometimes adds duplicate classes, such as .b-error).

Can you add a way to pass in false/"" values for those options?

Since you're doing a falsey assignment, empty strings and false don't work. You should explicitly check for null, so false and empty strings can be passed as values.

scope.options.errorClass = scope.options.errorClass || 'b-error';
scope.options.successClass = scope.options.successClass || 'b-loaded';

You would obviously need to adjust the method that adds the classes, so a bunch of empty strings aren't appended to the element's class list.

Let me know if you would like a pull request and I can get it done. 👍

Multi-serve images doesn't seem to be working

Hey,

Really nice plugin and I really want to use it. However I couldn't get the multi-serve images to work so I checked you demo page (http://dinbror.dk/blazy/) and I'm always getting the big bear image regardless of the screen size.

I'm using Windows 7 using Chrome 40.0.2214.111 and version 1.3.1 of bLazy.

Screenshot @ 340px:
blazy-340

Screenshot @ 1260px:
blazy-1260

Thanks,

Fitz

Options to add images in array .

Currently if we add images to DOM later on using say ajax, I will require to call the revalidate method.Suppose I already have the array of images due to some selector I had run or may be using directives .In this situation I can just pass the image element to the images array instead of asking for revalidate which reinitializes the plugin instance.
Some kind of public method will be of great help and would improve performance too.

Blazy.prototype.updateImageList = function(img){
images.push(img);
count ++;
validate();
};

Also now as I have already added the images I can have the validate as a public method to be called after adding the images.
Blazy.prototype.validate = function(){…

To enhance this further, suppose I am anyways selecting the images on the page to do some manipulation. So instead of asking the plugin to search the DOM again , I can just provide these selected array of elements as opion .
function createImageArray(selector) {
if(options.imagesArr.length > 0){
images = options.imagesArr;
count = images.length;
}else{
var nodelist = document.querySelectorAll(selector);
//converting nodelist to array
count = nodelist.length;
for(var i = count; i--; images.unshift(nodelist[i])){}
}

 }

Hope these help others as well and we can have them as a permanent feature for every one to take advantage of.

Create few instance of Blazy on the same page

Hi,
on the current pattern that you using its impossible to make few instance of Blazy on the same page,
the global variables images, options are shared between all instance of Blazy.
(I have different error/success scenario to handle)

Appending elements by ajax does'nt work - Blazy gets destroyed

Hi,

Blazy unbinds all events after all existing images gets loaded.

I'm dynamicaly appending images and applying .revalidate() to them. Unfortunatelly, before that, Blazy get's destroyed in .validate(). After commenting out this line, everything works as expected.

I see three possible resolutions:

  1. Do not destroy Blazy
  2. Make destroying a option
  3. Rebind events on .revalidate()

Add blazy on div scroll

Hi,

I would like add Blazy on my page, but the scroll is not on my body, but on "big container" (

.

So, blazy does not work because it must detect the scroll on the body.

Do you know how i can change this setting ?

Thank you ! :)

API docs: -moz- & -o- not needed

http://dinbror.dk/blog/blazy/#Multi

    .b-lazy {
        -webkit-transition: opacity 500ms ease-in-out 100ms;  /* Android =<4.3, iOS =< 6.1 */
/*         -moz-transition: opacity 500ms ease-in-out 100ms;
             -o-transition: opacity 500ms ease-in-out 100ms;
no longer needed http://caniuse.com/css-transitions */
                transition: opacity 500ms ease-in-out 100ms;
}

Thanks :)

use something other than offset as trigger?

Hi Bjorn,

Thank you for your work on this great script.

I'm pretty new to coding, so if you could let me know what I'm trying to achieve is possible, it would be very much appreciated.

I have a test server running at www.viiiyears.co.uk if you want to have a look.

I’m trying to use blazy to load images into: https://github.com/nolimits4web/Swiper

It's working on 1-3 slides depending on the size of the browser and offset value, but as they're at the top of the screen it triggers straight away.

If possible I would to have 8 slides with Blazy triggered on swipe to next slide. Is there anyway to have something other than the offset to trigger the image load?

Thank you,

Stuart

Feature suggestion: Callback when element in view

This is a feature request. Maybe I want to have a div that when scrolled to, causes an ajax request to execute & populate the div.

Ideal implementation would be to tell blazy to run some callback when an element becomes visible.

blazy already has elementInView(ele), so all it needs is the option to run a user defined callback instead of loadImage when the element becomes visible.

Implement breakpoints based on viewport width (or container width)

If working for example with bootstrap, it's would be perfect if breakpoints can be based on viewport width.
Suggestion:

  • Add option for viewport width

  • If set to true, use:
    var viewportWidth = window.innerWidth
    || document.documentElement.clientWidth
    || document.body.clientWidth;

    if(object.width >= viewportWidth) {
    source = object.src;
    return false;
    }

  • instead of:
    if(object.width >= window.screen.width) {
    source = object.src;
    return false;
    }

Doesn't trigger when needed

Excellent plugin, found an issue though...

1 - resize browser really small, so only 1-2 images are visible
2 - open a new tab & goto google
3 - maximize browser
4 - go back to original tab

Actual results - since the browser is now bigger, more images are shown, but blazy doesn't detect that more images are now visible. Although scrolling at least 1px triggers them to load

Expected results - blazy should not only fire on scroll event, but on browser resize, or when a tab becomes active (or at least fire an interval every few seconds to compare the current browser size to the last known size)

Multi-serving background images

Just wondering if this is something that's possible? It works fine in Chrome, but Safari and Firefox won't lazy-load different background images if I don't also set a data-src, which then overrides all the breakpoint image settings.

Do something after ajax request + append

Hi dinbror,

After having successfully used your nice script in a test file, I'm actually trying to use it on a specific part of my website.
When a user visit my portfolio, he lands on a page with a basic introduction text, so that while he's reading, I'm loading the full portfolio in ajax and then display it.
I would like BLazy to run after my ajax request, so it can handle the class of the new added images.

Here's a simplified version of my code:

function display_page(page_num){
    //Some code here will append a list of links + images etc. to a container of my website on ajax request success
}

$.ajax({
    url: ajaxURL,
    type: 'GET',
    dataType : 'json',
    data: {"action": "get_portfolio_data", "cat": cat, "excludedCat": excludedCat}
})
.done(function(data){
    //Some code
    display_page(cur_page);
}).then(function(){
    var bLazy = new Blazy({ 
        selector: '.taz_portfolio-item-visual',
        success: function(ele){
            console.log('OK!');
        },
        error: function(ele, msg){
            if(msg === 'missing'){
                console.log('Image is missing');
            }
            else if(msg === 'invalid'){
                console.log('Image is invalid');
            }
        }
    });
}).then(function(){
    taz_imageProtect(); // Prevent Right Click
}).then(function(){
    taz_adaptLargeImagesHeight(); // Adapt Images Size
}).then(function(){
    taz_imageZoom(); // Detect images that can be zoomed
}).then(function(){
    taz_detectExifAreas(); // Detect EXIF area on images
});

I've been able to find out that at this point, BLazy do not find the new appended ".taz_portfolio-item-visual" elements and then never enter to success or error. If (just for the test), I use "body" as selector, console.log clearly display it's invalid message.
Note that all the last functions added with .then() are perfectly working and are based on elements only present on the appended code.

Thanks in advance for your help!

offsetWidth and offsetHeight always 0 when using bLazy in ajax request.

v1.2.2
The offsetWidth and offsetHeight always returns 0 when using bLazy in an ajax request.

I know that the offset values will return 0 when the element = display:none; however this is not the case.

Whats happening is the following:
line 130

"if(ele.offsetWidth > 0 && ele.offsetHeight > 0) {

If these values are 0, then the image preloader keep loading forever and the image element never gets updated with the actual source.

by removing line 130 and 156, i managed to resolve the issue and everything works as expected, however im not sure what this check is actually for or if it should even be there as there is no else statement allowing to update or notify that there was an issue.

Regards
Shaughn

Option to ignore horizontal, load invisible and force load .

Hi,

I am using this plugin and its working great for me . Thanks ! .

A few things that i found useful and missing are -
1 - When a container has horizontal scroll , images do not get loaded till we scroll the page as horizontal scroll is on the div. I understand that this can be achieved using the container option but if i need to use a single instance of this plugin it becomes hard. Instead we can have a option to skip horizontal cheek .What I did in the older version was as follows -
return (
// inside horizontal view
(options.skipHorizontal || rect.left >= 0
&& rect.right <= winWidth + options.offset )
&&
(
// from top to bottom
rect.top >= 0 ……

2 – For issues with hidden images like in tabs, I see you have added a force variable in load. This makes the developer call it when every time its needed. Instead we could add this too as an option to load hidden images.
function loadImage(ele){
// if element is visible
if(options.loadInvisible || (ele.offsetWidth > 0 && ele.offsetHeight > 0)) {
…….

3 – A force parameted in load can be very useful too. In situation when I need to force load an image o matter in view port or not .Kind of preloading in carousels .For this I used the force variable as following.
Blazy.prototype.load = function(element ,force){
if(force || !isElementLoaded(element)){

It could be great if you add these options as they can give more flexibility depending on different scenarios to lot of us.

blazy blank images on gtmetrix.com mobile device ?

I am trying to implement blazy on my forums (avatar loading) so whipped up a test page first at https://community.centminmod.com/lazyload1.html?PageSpeed=off

it seems to work on my desktop Opera browser and on my Samsung S2 Android 4.42 chrome browser, but on gtmetrix.com nexus android device tests it comes up blank http://gtmetrix.com/reports/community.centminmod.com/TRtRmIzd ?

And on browser chrome test on gtmetrix desktop, seems all images 18 images still get loaded despite the viewport being smaller http://gtmetrix.com/reports/community.centminmod.com/APRCdI7C ??

Create NPM package

In addition to Bower package i suggest to add other popular repository - NPM.
It would be nice for Node.js users and frontenders who uses Browserify!

Example of simple multi-serve setup

I believe I got the setup correctly, it works as expected. Except one thing, the correct image is not showing on iPad mini retina.

Here is the setup:

 var bLazy = new Blazy({ 
            breakpoints: [{
                width: 900 // max-width
                , src: 'data-src-small'
            }
                         ]

        });

Small image is loaded for devices < 900, and regular image that is stored in data-src is provided for all other resolutions.

This is not working on iPad mini retina(landscape), it shows the smaller image, although clearly it should be serving the regular version through data-src="regular-image.jpg".

blazy does not change images source on window resize

I have tested it on my local. Image won't change source when window resize. I looked at demo page and try to resize window. But when it first load big-bear, it won't load small-bear image below 420px;

<img src=data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
                                     data-src="/assets/images/banner-1-lg.jpg"
                                     data-src-sm="/assets/images/banner-1-sm.jpg"
                                     data-src-mobile="/assets/images/banner-1.jpg"
                                     class="b-lazy">
var bLazy = new Blazy({
        breakpoints: [{
            width: 480
            , src: 'data-src-mobile'
        }
            , {
                width: 767
                , src: 'data-src-xs'
            }
            , {
                width: 991
                , src: 'data-src-sm'
            }
        ]
    });

CSS transitions don't work

Adding CSS transitions doesn't work, I'm using CSS from your example: http://dinbror.dk/blog/blazy/#Transitions

Seems like adding a CSS class with javascript prior to document.ready makes the browser immediately apply the finishing styles, skipping any transition (In Firefox at least). The two workarounds would be:

1 - Fire only on document.ready
2 - Apply a timeout to applying the "b-loaded" class:

setTimeout(function() {
                        ele.className = ele.className + ' ' + options.successClass;
                    }, 100);

Here's a simple test page that demonstrates this:

<html>
<head>
    <script src="/jquery-ui-1.10.4/jquery-1.10.2.js"></script>
    <style>
        #foo {
            border:10px red solid;
            transition:border 5s ease-in-out;
        }
        #foo.bar {
            border:10px green solid;
        }
    </style>

</head>
<body>
    <div id="foo">foo</div>
    <script>
        $(document).ready(function() {
            var el = document.getElementById('foo');
            el.className = el.className + ' bar';
        });
    </script>
</body>
</html>

The document.ready is deterministic. It can be replaced with a timeout, which makes the animations sometimes work, and sometimes get skipped. Trying to apply the new class immediately always results in the animation being skipped.

Uncaught TypeError: Cannot read property 'error' of undefined

Using these code

<script type="text/javascript" src="https://cdn.jsdelivr.net/blazy/1.4.1/blazy.min.js"></script>
<script>
    ;(function() {
        // Initialize
        var bLazy = new Blazy();
    })();
</script>

will thrown this error: Uncaught TypeError: Cannot read property 'error' of undefined.
Even with no elements in use. Even with 1.4.0.

document.ready

Looks like if other scripts like a jquery carousel fire after document.ready, and makes the page grow, some unloaded images are shown without being triggered until the user subsequently scrolls or resizes by at least 1px.

Possible solutions:

  1. polling - every 250ms or so, see if the offsets of any arbitrary element has changed from its last known value
  2. document.ready - wait until document.ready to bind blazy (I don't like it)
  3. no change - leave it up to the users to explicitly call bLazy.revalidate

Ability to check for un-loaded images and load from custom event?

Great plugin. Thanks.

I'm using it on a horizontal slider that uses transform3d to move things in the x axis.
As this transforms the panels in the x axis via transform3d and then directly updates the scroll position, there is no scroll event fired and so bLazy doesn't load in the images that were off screen previously.

Is there a way of firing bLazy from a custom event to 're-check' which images are loaded and re-load as needed?

Use container width instead of window width for lazy-load

When you use the container option when using a scrolling container, images are tested against the window width to determine whether they are in the viewport instead of against the container's dimensions.

In my case, I have a scrolling container that only fills up 2/3 of the screen, so there are a few images that aren't visible that still get lazy-loaded. Ideally they would only load as you scroll the container.

Thanks for this well-done lazy-loader!

Image in bootstrap modal does not load

Hi,

Really great plugin !
It works well in a container inside my main section.
But I'm experiencing a weird issue with bootstrap modal :
For example this is the modal :

        <div class="portfolio-modal modal fade" id="portfolioModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-content">
                <div class="close-modal" data-dismiss="modal">
                    <div class="lr">
                        <div class="rl"></div>
                    </div>
                </div>
                <div class="container">
                    <img class="b-lazy" src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" data-src="./img/01.jpg" data-src-small="./img/01.jpg" title="Image description" />
                </div>
            </div>
        </div>

In fact, nothing happens (i.e image source is still the same) when I launch the modal (via a button).
I've tried to call revalidate() on click but still no result ..

Thank you for your answer.

Jim

Resizing & breakpoints

Ability to trigger breakpoints based on viewport, not screen size
If my browser is resized to 400px, that should suffice to test a 400px breakpoint, without changing my screen's resolution. It should basically measure the width of the viewport, or the body element... not window.screen.width... or at the very least, maybe an option where I can pass a callback for determining the width

Respond to browser resizing
After it loads images, it destroys the data-src-small attributes, etc... but, why? Does this really hurt performance to keep the attribute around? I'd like to swap in successively larger images as a user incrementally increases his browser's size. Every resize should re-trigger the breakpoints. For example, flipping a tablet from portrait to landscape increases the width, and justifies loading the larger image.

Or, if you're dead-set on only triggering the breakpoints once, you should at least measure height & width, and use the larger of the two to compare to the breakpoint. This still does not account for the fact users can zoom in/out with control++/-, or change their screen resolution in their operating system.

Wrong src if angular.js used

If you use data-src="{{ var }}" you have to use (eg. jquery docready)
$(document).ready(function() {
var bLazy = new Blazy();
}

data-src somehow initialize element.src, so images loaded before scope.load and
after var dataSrc = ele.getAttribute(source) || ele.getAttribute(options.src);
dataSrc is this string: {[var}} (and not the value of the var)

It seems, that the problem is data-src attribute, because if I use this, it works well.
data-src2="{{var}}"
blazy.js
scope.options.src = source = options.src || 'data-src2';

I created a demo ( http://jsfiddle.net/ryo2vg88/3/ ), so it seems its an angular specific bug, and data-src is involved.

Anyway I report this issue angular/angular.js#13081

Re-size/orientation change with background images

Hi,

When I use b-lazy to lazy load a background image set as data-src this works well. But my site is responsive so I am specifying data-src (default e.g. 320px or should that be the largest?), medium (770px) and large (> 771). When I re-size or re-orientate the device, the new image is not being used - only the one used first time is applied.

Also the data-src attributes are destroyed when b-lazy has finished applying.

My div:

<div class="b-lazy" src="placeholder.jpg"
     data-src-medium="/images/600/Specifications.jpg')"
     data-src-large="images/template/landingpage/features/980/Specifications.jpg">
</div>

My java script:

<script type="text/javascript">
        jQuery(document).ready(function($j) {
            var bLazy = new Blazy({
                breakpoints: [
                {
                    width: 770, // max-width
                    src: 'data-src-medium',
                    mode: 'viewport'
                },
                {
                    width: 99999, // max-width
                    src: 'data-src-large',
                    mode: 'viewport'
                }],
                selector: 'img,.b-lazy', // all images
                offset: 200 // Loads images 200px before they're visible
            });
        });
    </script>

I tried the following, but as of yet have been unable to get it to work:

var isIOS = /safari/g.test(navigator.userAgent.toLowerCase());
            var ev = isIOS ? 'orientationchange' : 'resize';
            var diff = (window.innerWidth-window.innerHeight);
            $j(window).bind(ev,function(){
                setTimeout(function(){
                    if(diff*((window.innerWidth-window.innerHeight)) < 0)
                        orientationChanged();
                }, 500);
            });

            function orientationChanged() {
                console.log("orientation changed");
                $j('div.b-lazy').removeClass('b-loaded');
                bLazy.revalidate();
            }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.