Lazy load css animation

Simple Image Lazy Load and Fade

One of the quickest and easiest website performance optimizations is decreasing image loading. That means a variety of things, including minifying images with tools like ImageOptim and TinyPNG, using data URIs and sprites, and lazy loading images. It’s a bit jarring when you’re lazy loading images and they just appear out of nowhere which is why I love the fading in route. The page still shuffles if you aren’t explicitly setting image dimensions but the fade in does provide a tiny bit of class. I’ve seen many solutions which accomplish this (some not very good, like my old method) so I thought I’d share my current implementation.

The HTML

We’ll start by putting together the image tag with specifics:

Use data-src to represent the eventual URL.

The CSS

Any image with a data-src attribute should start as invisible and eventually transition the opacity:

Читайте также:  Чётные и нечётные числа

You can probably guess at this point what we’ll be doing with that attribute when an image loads.

The JavaScript

. which is removing the data-src attribute when the image has loaded:

[].forEach.call(document.querySelectorAll('img[data-src]'), function(img) < img.setAttribute('src', img.getAttribute('data-src')); img.onload = function() < img.removeAttribute('data-src'); >; >);

This solution does require JavaScript as a few of you have pointed out. For a fallback solution you could do this:

  
[].forEach.call(document.querySelectorAll('noscript'), function(noscript) < var img = new Image(); img.setAttribute('data-src', ''); img.parentNode.insertBefore(img, noscript); img.onload = function() < img.removeAttribute('data-src'); >; img.src = noscript.getAttribute('data-src'); >);

This is a super basic tutorial but considering I’ve seen so many other solutions, I thought I’d share what I’ve implemented; it works under every scenario I’ve tested, including History changes via AJAX (like my site does).

Of course this doesn’t take into account true scroll-based lazy load but that’s generally done by a plugin in your favorite JavaScript framework or a standalone component. If you’re looking for a simple solution, however, this is it!

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Use CSS animations on load or scroll.

sky-foundry/lazyanimate

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Use CSS animations on load or scroll.

yarn add lazyanimate # or npm install lazyanimate
import LazyAnimate from 'lazyanimate' const lazyAnimate = new LazyAnimate()

Lazy animate an element by adding a class of lazyanimate and a data-animate attribute with the CSS keyframes animation name:

 div class pl-s">my-div lazyanimate" data-animate pl-s">slide-in">div>

Add CSS animation keyframes and apply duration and timing function:

Note that you should not apply the animation name to your elements as lazyanimate will do this for you via the data-animate attribute.

/* CSS */ .my-div < animation-duration: 1s; animation-timing-function: ease-in-out; > @keyframes slide-in < from < transform: translateX(-60px); > >

Initialize lazyanimate in your JavaScript:

import LazyAnimate from 'lazyanimate' const lazyAnimate = new LazyAnimate() lazyAnimate.lazyAnimateAllOnLoad()

The data-animate attribute accepts either a string or a JavaScript object.

If a string is passed in, the element will have the CSS property animation-name applied to it when your lazyAnimate JS triggers it.

If a JS object is passed in, you can apply any css property prefixed with animation- .

You can also change the animation name using a media query string. You should have one key with a value of true which will be the fallback animation.

Loads all lazyanimate animations on load or instantly if already loaded.

import LazyAnimate from 'lazyanimate' const lazyAnimate = new LazyAnimate() lazyAnimate.lazyAnimateAllOnLoad()

Applies a CSS animation to an element based on it’s data-animate.

import LazyAnimate from 'lazyanimate' const el = document.getElementById('. ') const lazyAnimate = new LazyAnimate() lazyAnimate.lazyAnimateElement(el)

Applies lazy animate to all elements when intersection observer fires.

import LazyAnimate from 'lazyanimate' const scrollContainer = document.getElementById('. ') const thresholdPercent = 0.8 const lazyAnimate = new LazyAnimate() lazyAnimate.lazyAnimateOnScroll(scrollContainer, thresholdPercent)

About

Use CSS animations on load or scroll.

Источник

Fade in lazy loaded images with React and CSS – a quick guide

Senior Engineer Mindset cover

Say you want to lazy load some images on your website. You don’t want them to just pop into existence and scare the user. A nice fade in effect works much better.

Here’s the problem: There’s no good pre-built React component for this. Or I suck at finding it.

There’s a react-lazyload, which does the lazy loading part for you. It keeps components from mounting into the DOM until the user actually sees them.

This helps make your website faster to load. No need to load large images until a user can actually see them.

But the default experience can be jarring. When images finally load, they just pop into view.

react-lazyload offers a fade-in example, but it’s outdated and doesn’t work with modern libraries. And it’s cumbersome to use.

So I built a general FadeIn component. I’ll opensource it, but it needs some polish first, and I’d like your opinions on how to make it better.

The component is just 40 lines of code. Pretty simple.

class FadeIn extends React.Component
state =
loaded: false,
>;
onLoad = () => this.setState( loaded: true >);
render()
const height, children > = this.props,
loaded > = this.state;
return (
lazyload height=height> offset=150>>
transition in=loaded> timeout=duration>>
(state) => (
div style= . defaultstyle, . transitionstyles[state] >>>
children(this.onLoad)>
/div>
)>
/transition>
/lazyload>
);
>
>
FadeIn.propTypes =
height: PropTypes.number,
children: PropTypes.func,
>;

FadeIn keeps local loaded state to keep track of what to show. false means «stay transparent», true means «fade to full opacity».

It uses react-lazyload’s LazyLoad component to handle the lazy loading part, and Transition from react-transition-group to drive the CSS transition for fading in. This is the part that’s changed a lot since the official fadein lazyload example.

Using the children render function approach, you can ask FadeIn to render anything you want. It gets wrapped in a div that handles the fade effect.

All you have to do is trigger the onLoad callback once your content is ready. When your image is done loading for example.

fadein height=400>>
onLoad =>
img class=cx('img')> src=subheader2> onload=onLoad>>
>
/fadein>

You render , give it a height so things don’t jump around, and pass a children function that takes an onLoad callback. When you’re ready to trigger the transition, you call onLoad and FadeIn does its thing.

Did you know onLoad was a built-in DOM callback that all browsers support? I had no idea.

onLoad is important because without it the FadeIn transition might end before the image has even come down the pipe. That’s the issue I was facing at first when I livecoded this.

Recommendations?

I want to opensource this. I know it’s simple, but it could save people like an hour of their time. That’s worth it, right?

What else does it need to do? What should I name it? Would you use it?

Did you enjoy this article?

Learned something new?
Read more Software Engineering Lessons from Production

I write articles with real insight into the career and skills of a modern software engineer. «Raw and honest from the heart!» as one reader described them. Fueled by lessons learned over 20 years of building production code for side-projects, small businesses, and hyper growth startups. Both successful and not.

Software Engineering Lessons from Production

Join Swizec’s Newsletter and get insightful emails 💌 on mindsets, tactics, and technical skills for your career. Real lessons from building production software. No bullshit.

«Man, love your simple writing! Yours is the only newsletter I open and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌»

~ Ashish Kumar

Senior Engineer Mindset cover

Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Have a burning question that you think I can answer? Hit me up on twitter and I’ll do my best.

Who am I and who do I help? I’m Swizec Teller and I turn coders into engineers with «Raw and honest from the heart!» writing. No bullshit. Real insights into the career and skills of a modern software engineer.

Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.

Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev

Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization

Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections

Want to brush up on modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog

Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️

Источник

Enhancing HTML 5 Lazy Loading With CSS and Minimal JavaScript.

What is “Lazy Loading” you ask? It’s a technique by which images or other content on a website is only loaded when needed, instead of all at once when you first visit the page. This can result in sites being useful and usable by users long before everything has finished loading. Why waste bandwidth and time loading images that are off the bottom of the screen? Only load them once you scroll to them and save everyone some time.

For a long time a lot of broken, non-semantic, inaccessible trickery has been done in JavaScript to accomplish “lazy loading” of images. Most of the systems required bloated markup, didn’t gracefully degrade well, often duplicated the image information twice with , and a whole host of other trickery.

This trickery and over-use of scripting has for a long time made me shy away from these types of effects, rejecting them as flawed/broken garbage. My knee-jerk reaction when someone asked being a just plain “no… you’re REALLY better off not doing that.”

But improvements in web technologies have made much of the excess scripting people use obsolete, and as such I had to re-evaluate this position. I gave it a try to make sure that I wasn’t out of date, and full of **** on the topic. Sometimes you really need to checkity-check yourself before…

And what I found was that HTML 5 has given us a mechanism for this in the form of the loading=”lazy” attribute. If you’re unfamiliar with it, I suggest you read the MDN article on the topic:

Lazy loading

Lazy loading is a strategy to identify resources as non-blocking (non-critical) and load these only when needed. It’s a…

No more screwing around making multiple copies of the image code, adding all sorts of JavaScript cloning / element creation, etc, etc. Just put the image in, set the attribute, and boom, working lazy loading. In supported browsers.

Whilst this does give us the basic mechanism with full graceful degradation, it doesn’t really provide a lot in the way of “control” over how the image appears once loaded. A simple fade in, scale in, or other such animations would/could be added…

Источник

Оцените статью