Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Last active April 17, 2020 09:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathansmith/58f041ad371cdda3b851c252d6b64781 to your computer and use it in GitHub Desktop.
Save nathansmith/58f041ad371cdda3b851c252d6b64781 to your computer and use it in GitHub Desktop.
Prevent CSS animations before page load.
/*
Inspired by this post…
https://css-tricks.com/transitions-only-after-page-load
I didn't want to have to add something to
the page initially, only to remove it later.
Instead, I'm adding a "positive" flag via JS
and am simply ignoring all animations and
transitions if the flag is not present.
*/
html:not([data-has-css-animation="true"]) * {
animation: none !important;
transition: none !important;
}
/*
Used like so…
```
import cssAnimation from './cssAnimation';
cssAnimation.init();
```
*/
// ==========
// Constants.
// ==========
const event = 'DOMContentLoaded';
const attr = 'data-has-css-animation';
const d = document.documentElement;
const w = window;
// ==============
// Event handler.
// ==============
const handleLoad = () => {
w.requestAnimationFrame(() => {
d.setAttribute(attr, true);
});
};
// ======================
// Remove event handlers.
// ======================
const unbind = () => {
d.removeAttribute(attr);
w.removeEventListener(event, handleLoad);
};
// ===================
// Add event handlers.
// ===================
const init = () => {
// Prevent doubles.
unbind();
w.addEventListener(event, handleLoad);
};
// ==============
// Expose object.
// ==============
const cssAnimation = {
init,
unbind,
};
// =======
// Export.
// =======
export default cssAnimation;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment