Last active
April 17, 2020 09:42
-
-
Save nathansmith/58f041ad371cdda3b851c252d6b64781 to your computer and use it in GitHub Desktop.
Prevent CSS animations before page load.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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