Giter VIP home page Giter VIP logo

yall.js's Introduction

yall.js (Yet Another Lazy Loader)

Uncompressed size. gzip size. Brotli size.

yall.js is a SEO-friendly lazy loader for <video> elements as well as CSS background images. It works in all modern browsers. It uses Intersection Observer where available. yall.js can also monitor the DOM for changes using Mutation Observer to lazy load elements that have been appended to the DOM after initial load, which may be desirable for single page applications.

yall.js 4 removes lazy loading for <img>, <picture>, and <iframe> elements, as native lazy loading covers these use cases. However, yall.js 4 retains the ability to lazy load autoplaying <video> (ala animated GIFs), lazy loading <video> element poster images, as well as CSS background images.

To use yall, grab yall.min.js (or yall.min.mjs if you're the modern sort) from the dist directory and slap it on your page. You can also install it with npm:

npm install yall-js

Usage

This is version 4 of yall.js, and introduces a named export named yall rather than a single default export:

// Import y'all
import { yall } from "yall-js";

// Invoke!
yall();

The above syntax is sufficient if you don't want to pass in any options. If you do want to specify options, you'll need to use a slightly more verbose syntax:

// Import y'all
import { yall } from "yall-js";

// Invoke!
yall({
  observeChanges: true
});

From there, lazy loading elements depends on what you want to lazy load. Let's take a look at what you can do with it.

<video>

yall.js covers two possible lazy loading patterns for video.

Lazy-loading videos intended as replacements for animated GIFs

yall.js can lazy load <video> elements intended to replace animated GIFs with autoplaying videos:

<video class="lazy" autoplay loop muted playsinline>
  <source data-src="video.webm" type="video/webm">
  <source data-src="video.mp4" type="video/mp4">
</video>

The pattern is largely the same as it is with <picture>, only the lazy class is applied to the <video> element. Tip: If you're embedding videos that don't emulate animated GIFs (i.e., non autoplaying video), it's better to not lazy load them. Instead, use the preload attribute to defer loading of video content. Please also note that video autoplay policies can change at any time, meaning your video may not autoplay on some platforms! Such behaviors are not bugs, but rather features designed to respect users' bandwidth and preferences. Filing issues related to video autoplay issues will likely be rejected, as yall.js can't (and won't) override browser policies.

Lazy-loading poster placeholder images for non-autoplaying video

Sometimes you have video you'd rather not autoplay, such as those with an audio track. Or, perhaps you want to be more considerate of your user's bandwidth (how nice of you). In these cases, the poster attribute can be used to load a placeholder image. However, these images can also be rather large, especially if you have a number of videos on the page that use this pattern. You can lazy load poster images with the following markup pattern:

<video class="lazy" data-poster="placeholder.jpg" controls preload="none">
  <source src="video.webm" type="video/webm">
  <source src="video.mp4" type="video/mp4">
</video>

This pattern is slightly different than the one before it. Because we're not trying to emulate animated GIFs, we've removed a number of attributes from the <video> element that aren't necessary in this case:

  1. We've done away with the usual data-src attribute, and specified preload="none" to ensure the browser doesn't preload any portion of the video (which, depending on the browser, can't be guaranteed).
  2. To lazy load the poster image itself, we specify the image to load in a data-poster attribute.
  3. The controls attribute is added here to allow the user to control video playback.

Note: For the sake of your users, don't mix the above markup patterns. If a video is going to use autoplay to replace an animated image, lazy loading a placeholder image via data-poster isn't necessary. Furthermore, if you're unsure of what to do, let browsers handle this stuff and don't use yall.js to manage loading of videos at all!

CSS images

Last, but not least, you can use yall.js to lazy load images referenced in CSS. This might be useful if you have a very large background-image you'd like to defer. Proper use of this feature requires both HTML and CSS. To start, let's say you have a <div> that loads a very large masthead background-image:

<!-- I bet this loads a giant stock photo! -->
<div class="masthead lazy-bg"></div>

The key here is the lazy-bg class, which is a class yall.js looks for (and can be changed in the options). When yall.js sees elements with this class, it will remove that class and replace it with a class of lazy-bg-loaded (also changeable in the options). From here, it's up to you to author CSS that makes use of this class to swap the image in. Such CSS might look like this:

/* Pre-lazy loading styles */
.masthead {
  background: #e6e6e6; /* A little placeholder color */
  height: 16.66vw;
  margin: 0 0 1rem;
}

/* BAM! Lazy loaded! */
.masthead.lazy-bg-loaded {
  background: url("masthead.jpg");
}

This works because, unlike HTML which loads most resources regardless of their visibility, CSS loads resources only if the current layout builds a CSSOM which includes them. That means if your document's style tree changes later on to request a background image, the browser will fetch it the moment the change is applied. Leaning on this behavior is more sensible than using a mess of data- attributes pointing to possible image candidates, which could potentially add a bunch of extra markup and introduce edge cases that are difficult to code for.

What about users without JavaScript?

Slap on some <noscript>:

<!-- A `<video>` example: -->
<video class="lazy" preload="none" autoplay loop muted playsinline>
  <source data-src="video.webm" type="video/webm">
  <source data-src="video.mp4" type="video/mp4">
</video>
<noscript>
  <video preload="none" autoplay loop muted playsinline>
    <source src="video.webm" type="video/webm">
    <source src="video.mp4" type="video/mp4">
  </video>
</noscript>

<!-- A `<video>` example: -->
<video class="lazy" preload="none" autoplay loop muted playsinline data-poster="img/video-poster.jpg">
  <source src="video.webm" type="video/webm">
  <source src="video.mp4" type="video/mp4">
</video>
<noscript>
  <video preload="none" autoplay loop muted playsinline poster="img/video-poster.jpg">
    <source src="video.webm" type="video/webm">
    <source src="video.mp4" type="video/mp4">
  </video>
</noscript>

Then place a no-js class on the <html> element:

<html class="no-js">

Finally, add this one line <script> before any <link> or <style> elements in the document <head>:

<!-- Remove the no-js class on the <html> element if JavaScript is on -->
<script>document.documentElement.classList.remove("no-js")</script>

Normally, this script will remove the no-js class from the <html> element as the page loads, but if JavaScript is turned off, this never happens. From there, you can add some CSS that hides elements with a class of lazy when the no-js class is present on the <html> element:

/* Hide .lazy elements if JavaScript is off */
.no-js .lazy {
  display: none;
}

To see all these examples in action, clone the repo, install packages, run npm test, and check out the demos on your local machine at http://localhost:8080.

API options

When you call the main yall initializing function, you can pass an in an options object. Here are the current options available:

lazyClass

default: "lazy"
The element class used by yall.js to find elements to lazy load. Change this is if a class attribute value of lazy conflicts with your application.

lazyBackgroundClass

default: "lazy-bg"
The element class used by yall.js to find elements to lazy load CSS background images for. Change this if you'd prefer not to use the default.

lazyBackgroundLoaded

default: "lazy-bg-loaded"
When yall.js finds elements using the class specified by lazyBackgroundClass, it will remove that class and put this one in its place. This will be the class you use in your CSS to bring in your background image when the affected element is scrolled into the viewport.

threshold

default: 200
The threshold (in pixels) for how far elements need to be within the viewport to begin lazy loading.

events

default: {}
An object of events that get sent directly to addEventListener for each element to be lazy loaded. Rather than building an opinionated, bespoke event management system, this system gets out of your way and lets you to specify whatever events are possible to bind with addEventListener. Here's an example below:

yall({
  events: {
    // The object key is sent as the first argument to `addEventListener`,
    // which is the event. The corresponding value can be the callback if you
    // don't want to send any options to `addEventListener`.
    load: function (event) {
      if (!event.target.classList.contains("lazy")) {
        event.target.classList.add("yall-loaded");
      }
    },
    // If we want to pass options to the third argument in `addEventListener`,
    // we can use a nested object syntax like so:
    error: {
      // Here, the `listener` member is the callback.
      listener: function (event) {
        if (!event.target.classList.contains("lazy") && event.target.nodeName == "VIDEO") {
          event.target.classList.add("yall-error");
        }
      },
      // The option below is sent as the third argument to `addEventListener`,
      // offering more control over how events are bound. If you want to
      // specify `useCapture` in lieu of options pass a boolean here instead.
      options: {
        once: true
      }
    }
  }
});

Events for yall.js are bound at initialization time (often DOMContentLoaded). This means that some events could fire multiple times, depending on the event. For instance, in the above load event example, you can see that we check for the default class of lazy on the element. This is because the load event could fire when the initial image placeholder loaded (if one is specified) and when the final image is lazy loaded.

The advantage of this approach is that you can do pretty much anything you want in any of the events on the elements yall.js observes. The disadvantage is that it places the responsibility squarely on you to manage events. If you think yall.js has a bug in this behavior, do your due diligence to research whether your event callback code is buggy before filing issues.

observeChanges

default: false
Use a MutationObserver to monitor the DOM for changes. This is useful if you're using yall.js in a single page application and want to lazy load resources for markup injected into the page after initial page render.

observeRootSelector

default: "body"
If observeChanges is set to true, the value of this string is fed into document.querySelector to limit the scope in which the Mutation Observer looks for DOM changes. The <body> element is monitored by default, but you can confine the observer to any valid CSS selector (e.g., #main-wrapper).

mutationObserverOptions

default: { childList: true, subtree: true }
Options to pass to the MutationObserver instance. Read this MDN guide for a list of options. It's very possible that changing this value could result in yall.js failing to lazy load resources that are appended to the DOM later on.

Words of advice

Unlike previous versions of yall-js, compatibility back to IE 11 is no longer a goal. If you need compatibility with older browsers, install the previous release of yall.js like so:

Also, it is not this script's job to minimize layout shifts for you. Use appropriate width and height attributes, styles, and lightweight placeholders for your images.

For <video> elements, avoid lazy loading a placeholder with the data-poster attribute for autoplaying videos and just use poster. On the other hand, do consider lazy loading a placeholder image with data-poster for non-autoplaying videos. Or you can opt not to use a poster image. Your website, your call.

Also, do not lazy load resources that are likely to near the top of the page—or "above the fold", as it were. Doing so is an anti-pattern in that those resources will not begin loading until yall.js has been loaded, which may take much longer than if those resources were loaded normally. Such a pattern will negatively affect your page's LCP.

Contributing

Please read the contribution guidelines. If you think I'm some kind of grumpy crank after reading that, please remember that this is a hobby project you can use for free.

yall.js's People

Contributors

adhocore avatar anthonygore avatar asvny avatar chrisdemars avatar dependabot[bot] avatar kamranayub avatar malchata avatar mcmimik avatar mobe91 avatar peterchaplin avatar radfahrer avatar rkumorek avatar sherms 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

yall.js's Issues

Update [email protected]

Hi,

Thanks for this usefull tool !

When i install yall with yarn, i have the message below :
warning yall > [email protected]: This version is no longer maintained. Please upgrade to the latest version.

Please can you update joi version ?
Thanks

EDIT : Me again :), when i compile with Webpack, i have this messages :

ERROR  Failed to compile with 2 errors                                                                                                                    09:33:28

These dependencies were not found:

* dns in ./node_modules/isemail/lib/index.js
* net in ./node_modules/joi/lib/string.js

Are this libraries not installed with yall ?

Add an onYallLoad callback option?

Hi - thanks for the useful script. I have a feature suggestion for you.

In my case I am periodically (re)loading elements containing images in the page. Simply adding the lazy class on all images, and then triggering yall works okay but the placeholder image (which in this case is not derived from the desired image) flickers briefly as a result.

My approach to resolving this is to 'remember' which images have been previously seen & not to lazy load those.

Implementing that remembering process simply requires a callback(imageSrc) call at the end of the yallLoad function.

That might be generally useful for other elements too? And other users?

Regards,
Gordon

Browser loading the <noscript> image files by default even if they are hidden by 'display:none'

HI malchata,

We are using your suggestion of noscript elements everywhere we are using lazy loading using yall.js. We noticed that yall.js seems to be working as expected when the browser can run javascript. BUT, it seems those lazy loaded images are all being preloaded any way by the browser because of how the browser treats the noscrip elements. Apparently, when the browser can run js, the noscript elements still makes the browser/chrome to download the image inside the .

...

<img class="lazy sampleimage" data-src="image1.jpeg" src="PLACEHOLDER-IMAGE.png" alt="This is a image when browser can do js.">
<noscript>
        <img src="image1.jpeg" class=" sampleimage" alt="This is image when browser cannot do js.">
</noscript>

...
I was thinking we can add a simple js-code to just display:none all elements so they will not require their child images to be loaded by the browser. Also, when the browser cannot run js, this code will not run and we will have the element to fall back to display the img

While it seems to be a quick fix, I am not sure if this is the best approach. I'd like to have your opinion on how to handle the issue of browser loading the image files by default.

npm install can fail on windows

npm install can fail for yall.js because of this step:

rm -rf ./dist

rm may or may not be a valid command on windows depending on the console used

I ran it from a Powershell console and even though rm is aliased it still failed at that command with this error message:

 [email protected] postinstall C:\Code\..\node_modules\yall-js
> npm run build


> [email protected] build C:\Code\..\node_modules\yall-js
> npm run clean && npx rollup -c


> [email protected] clean C:\Code\..\node_modules\yall-js
> rm -rf ./dist

'rm' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] clean: `rm -rf ./dist`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] clean script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\..\AppData\Roaming\npm-cache\_logs\2019-07-29T15_06_46_005Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `npm run clean && npx rollup -c`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\..\AppData\Roaming\npm-cache\_logs\2019-07-29T15_06_46_044Z-debug.log
npm WARN rollback Rolling back [email protected] failed (this is probably harmless): EPERM: operation not permitted, lstat 'C:\Code\..\node_modules\fsevents\node_modules'
npm WARN assets No description
npm WARN assets No repository field.
npm WARN assets No license field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] postinstall: `npm run build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\..\AppData\Roaming\npm-cache\_logs\2019-07-29T15_06_46_577Z-debug.log

This issue can be avoided by running this command:

npm install --ignore-scripts

However, the npm script should probably be tweaked to avoid the error. Perhaps the dist folder should be allowed to live?

observeRootSelector not working for list of IDs

From the manual of yall.js "... you can confine the observer to any valid CSS selector".
However it doesn't work if I use a list such as "#id1,#id2,#id3,#id4".
It works with a single ID such as "#id1".

If the uncompressed version is used: js errors

When i use the uncompressed Version (yall.js) errors appear in the console. In Internet Explorer 11 and on iPad, lazy loading then does not work.

For example Line 39 causes a mistake, because "...userOptions" it is actually a comment :

  // Default options, merged with user options.
  const options = {
    lazyClass: "lazy",
    lazyBackgroundClass: "lazy-bg",
    lazyBackgroundLoaded: "lazy-bg-loaded",
    throttleTime: 200,
    idlyLoad: false,
    idleLoadTimeout: 100,
    threshold: 200,
    observeChanges: false,
    observeRootSelector: "body",
    mutationObserverOptions: {
      childList: true,
      subtree: true
    },
    ...userOptions
  };

(If I want to compress the uncompressed file, errors also appear.)

Only "lazy" class?

Hello, first, thank you very much for the time you have spent, spend, on yall.

Is there any way to tell yall to observe more than one class?.
I mean default is "lazy", anyway I can add one more.

Scenerio:
Iframes (youtube videos) created in an editor (Quill.js) as part of a post (not wp) and no chance to change classes or add them because it is javascript and when they, iframes, are loaded in page with their own class I have no chance to add "lazy" unless I edit the script, which is far away from my knowledge.

Thank you and all the best!

Don't use multiple IntersectionObservers

As @xPaw pointed out in #9, the current IntersectionObserver code creates multiple instances of the IntersectionObserver class. The current solution does work, and it is still more performant (in my cursory testing) than binding scroll handlers and such, but it would be more performant to have a 1:many relationship between observers and elements, rather than a 1:1 relationship as currently exists.

Encapsulated code

It looks like there are three functions exposed to the global namespace (from the minified version).
Is it possible to encapsulate the code and only expose the 'yall' function to the global namespace?

Thanks

Create an ultra-modern version?

Since support for IntersectionObserver has been implemented, I've been wondering if there's interest in a version of yall.js that only uses IntersectionObserver and doesn't fall back to binding scroll/resize event listeners for older browsers. At this time (22 October, 2017), IntersectionObserver support is at about ~63%: http://caniuse.com/#feat=intersectionobserver

Some cursory tinkering reveals that relying only on IntersectionObserver could slim this script down to 726 bytes. Thoughts?

Google Page Speed still asking to defer offscreen images

Hi fellas,

I've implemented yall on our company site, i have included the polyfill.io script in the example but google page speed is still telling me to defer off screen images even though they are.

Any ideas as to why? Every image has the lazy class attached and the data-src URL. I'm baffled.

Thanks

SVGs not loading in OSX & iOS Safari

SVG files fail to load in Safari. The Javascript console has this error:

Unhandled Promise Rejection: EncodingError: Invalid image type.
[N] (anonymous function)
[N] promiseReactionJob

I made a test on plunker. You can use it to test here: https://next.plnkr.co/plunk/GJEd9DNdH9xRHzJanfau

Essentially the test loads a .jpg into the src attribute and an svg into the data-src attribute. I pasted the latest yall.js version (2.1.0) into the plunk script file and added jquery 3.1.1 above it.

images class attribute is lost

Once yall has executed, my images are losing it's class property and a width and height attribute is forced to appear.

That fails with my needs, because I'm using that image class to use it as object-fit:'cover' in it's className.

How do you plan to handle dynamically loaded HTML

Under the Limitations section I noticed you mentioned that this library does not work for dynamically injected markup, however the library should support this at some point in the future; I was wondering if you had a plan for implementing this. It seems like using MutationObserver is a good idea, as it is widely supported (including back to IE11), and should be able to efficiently listen to DOM mutations. I'm guessing we could observe on document.body or something and listen for childList mutations, determine if a child has the .lazy class, and therefore should also be observed?

Maybe we could make mediaObserver a variable global to this module, so we could .observe future elements that our MO detects. Thoughts?

Broken loop in yallApplyFn

yallApplyFn uses a for ... in loop to loop over an array. However, this loop also considers all enumerable object keys and not only array indices. This can break the intended functionality in cases where e.g. Array.prototype has been extended by custom keys.

Puppeteer script fails, fetch as google fails

I implemented Yall, and it loads very nicely on my desktop, and even the Puppeteer screenshot, but the script fails because the comparison is different, and Fetch as google shows a blank.

This is what Google says:
https://developers.google.com/search/docs/guides/lazy-loading

Test
After you set up your implementation, you should make sure it works correctly. One way you do this is by using a Puppeteer script to locally test your implementation. Puppeteer is a Node.js library for controlling headless Chrome. To run the script, you'll need Node.js. Use the following commands to check out the script and run it:

So without scroll events, it fails.. I don't know what reason? It is using intersection observer, but still does not work through this script. Worse is that Google fetch fails completely...

I even tried to Polyfill, and it doesn't load in fetch as Google. Very strange.

Any ideas? Have you tested this on Fetch as Google and Puppeteer?
Only Zepto Lazy was able to load properly with Fetch as Google. Even the famous verlok/lazyload did not work, but the old Fetch as Google is gone now. It would load only the first image. Now we can never know if the fetch works properly for 2nd, 3rd images, etc.. only first.

Just to note, the Puppeteer screenshot with scroll does end up loading the images. But the one without scroll is missing them.

I have yet to find one script that passes that test, and most other don't pass the fetch as Google test.

Seems like this lazy loading is more of a headache than anything concerning compatibility and Google. I've spent so much time trying to find a good solution.

option to bypass `classList` mutation?

hey @malchata

it would be useful if yall offered an option to avoid classList mutation. it would require a bit more internal book-keeping, likely via a couple Set objects, e.g. bgLoaded and srcLoaded.

the main motivation for this is when used with a virtual-dom lib. let's say hyperscript creates an element h("img", {class: "lazy", "data-src": "123.jpg"}) but then some action causes a redraw that results in h("img", {class: "lazy active", "data-src": "123.jpg"}). the vdom lib does the diff against the prior vnode and simply resets the className when it detects the change. if yall is relying on lazyBackgroundLoaded being present or lazyClass being absent, this would break these assumptions.

Lazy Loading Fails With Polyfil

When using the intersection-observer polyfill package from NPM, lazy loading doesn't work. The compatibility check here

if (io in win && `${io}Entry` in win && "isIntersecting" in win[`${io}Entry`].prototype) {
seems to be failing.

Implement IntersectionObserver

This article by Dan Callahan alerted me to the existence of IntersectionObserver, a browser feature that may give us a better alternative to doing checks with getBoundingClientRect.

Can div or span be used instead of img?

Does this plugin support using a div or span instead of an img tag to lazy load an image? My use case is that I don't want to use a placeholder image and would like to use a generic div or span element to indicate where the lazy-loaded image should render because I don't want to use an img element where it is it not semantically valid to do so.

yall doesn't seem to work on iOS

Hi,
while testing yall's lazy loading on iOS, we found out, that no image was loaded there at all. I thought maybe it's something with my page setup. However, I create a small JSbin which allows reconstructing the issue outside the original environment.

I only see the placeholder image but the lazy-loaded nature image never appears in iOS:
https://jsbin.com/gexusareze/edit?html,output

I tested it on iOS 9 through Browserstack. Can you please check that issue?

Thank you,
bb

Firefox slider with lazyloading doesnt work

Firefox version 68 (should happens in other versions as well)
Yall version 3.1.1
jQuery FlexSlider version 2.2.2

Only the first slide is lazy loaded and the rest shows blank or default placeholder always.

We use observer yall({ observeChanges: true }) with polyfill.

We however noticed that if we scroll down and again scroll up the latest slider in view is loaded (but not all the others)

null is not an object (evaluating 't.tagName')

n(e){if("IMG"===e.tagName){var t=e.parentNode;"PICTURE"===t.tagName&&i(t.querySelectorAll("source")).forEach(function(e){return s(e)}),s(e)}

I found a problem since I start using yall.js
It's tracked by my Sentry and most of the issues came from Safari/IOS/Iphone.

image

2.3.2 not working with IE11

I am getting an Unspecified Error here: ed.top<=innerHeight+z
I am using the yall.min.js 2.3.2. The error happens after clicking the back browser button.

Images NOT showing if you use browser Back button to go back to the previous page with yall lazy loaded images

Images NOT showing if you use browser Back button to go back to the previous page with yall lazy loaded images. That previous page loaded fine initially, but then you click on a link and navigate to second page ... then you hit browser back button (chrome and edge) the images that you saw on the first page are not visible anymore and instead, in developer tools you see the 1px-1px placeholder.jpg image in place of the real image.
Maybe we are doing something wrong. Could you please advise? Thanks a lot.

TS

SCRIPT1028: SCRIPT1028: Expected identifier, string or number

Microsoft Edge error

SCRIPT1028: SCRIPT1028: Expected identifier, string or number
yall.js (137,5)

I also get

SCRIPT5009: SCRIPT5009: 'yall' is not defined

My document works sort of in Google Chrome (see #24) but in Microsoft Edge, any images that are controlled with yall.js are not working.

My code

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

Just before closing body tag (</body>)

<script src="js/yall.js"></script>
<script>document.addEventListener("DOMContentLoaded", yall);</script>

Image not loaded in random cases on Safari.

Hi,
I am experiencing an issue where is some random cases image is not loaded in Safari.
yall.js 3.1.1
Safari 12.1.1

Here's a quick screen recording of the issue:
https://drive.google.com/file/d/1X_tKFQF4373sqryXPo6gfT1i_gUna8C5/view

When I scroll back to that specific image which is not loaded it then gets loaded.
Also this is not happening for a specific image, but for a random image on every page refresh.

document.addEventListener("DOMContentLoaded", function () {
        yall({
            threshold: 1800
        });
 });

Is anyone having the same issue?

More rigorous viewport checks.

Currently, yall.js checks if images are beneath the viewport, but not above. This leads to scenarios where, if a page is reloaded or a deep link is hit, any images above the viewport are loaded when yall inits.

For better performance, yall.js should check if an image is below or above the viewport to avoid loading images that are above, but still out of the user's viewport.

Hardcoding strings to variables might not actually produce smaller gzip output

From uglifyjs' repo:

If your code is very hand-optimized concerning var declarations, this lifting variable declarations might actually increase size.

There's absolutely no need to have shortened variable names in source code as the minified code has mangled variables anyway. It will increase readability a lot by having properly named variables (the minified output will still be the same size).

Doesn't seem to work in MS Edge

the current version does not seem to work in MS Edge. i can see placeholders, but loading of images does not take place. Is there a work-around, or is there any plan to get it working

Background images inside style attributes

Hi there,

This is a bit like #19 but not exactly.

I'm trying to automate some code to lazy load images on wordpress sites, however, a wordpress plugin doesn't always have easy control over the css code on the site or it's structure. But, we can parse the html and rewrite portions of the html code relatively easily.

Is there any way we can lazy load the image below?
<div class="tve_post_grid_image_wrapper" style="background-image: url(https://example.com/wp-content/uploads/2017/10/Coffee-Subscription-Boxes.jpg ); height: 195px">

I was thinking that rewriting the html to something like this, and then let yall.js deal with it, makes sense:
<div class="tve_post_grid_image_wrapper lazy-bg" style="background-image: url('data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7') data-background-image: url(https://example.com/wp-content/uploads/2017/10/some-image.jpg ); height: 195px">

Is this something you could add in the future, or do you suggest some other method that doesn't involve creating extra css classes for the background images, or replacing the style attribute?

Add methods to attach/detach lazy loading

Would appreciate methods that would allow to temporarily suspend lazy loading. In my case this is important when smooth scroll animation is running. This makes scroll animation jerky and lazy-loads images, which are not neccessary.

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.