Last active
November 30, 2018 06:33
-
-
Save bpceee/3ebf2778e43642128b9ad1070ea786f4 to your computer and use it in GitHub Desktop.
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
let styleEl; | |
let keyframeID = 0; | |
const insertionObserver = function(selector, callback) { | |
if (!styleEl) { | |
styleEl = document.createElement('style'); | |
document.head.appendChild(styleEl); | |
} | |
const curKeyframeName = `insertionObserver${keyframeID++}`; | |
const keyframesRule = `@keyframes ${curKeyframeName} { from { opacity: 0.99; } to { opacity: 1; } }`; | |
const styleRule = `${selector} { animation-duration: 0.001s; animation-name: ${curKeyframeName}; }`; | |
const rulesIdx = styleEl.sheet.length; | |
styleEl.sheet.insertRule(keyframesRule); | |
styleEl.sheet.insertRule(styleRule); | |
const listener = (event) => { | |
if (event.animationName === curKeyframeName) { | |
callback(event); | |
} | |
} | |
document.addEventListener('animationstart', listener, false); | |
return () => { | |
styleEl.sheet.deleteRule(rulesIdx); | |
styleEl.sheet.deleteRule(rulesIdx + 1); | |
document.removeEventListener('animationstart', listener, false); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment