Skip to content

Instantly share code, notes, and snippets.

@bpceee
Last active November 30, 2018 06:33
Show Gist options
  • Save bpceee/3ebf2778e43642128b9ad1070ea786f4 to your computer and use it in GitHub Desktop.
Save bpceee/3ebf2778e43642128b9ad1070ea786f4 to your computer and use it in GitHub Desktop.
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