Skip to content

Instantly share code, notes, and snippets.

@aleclarson
Created November 14, 2017 01:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aleclarson/ac6456c75edae9fe9d9b6938142a065b to your computer and use it in GitHub Desktop.
Save aleclarson/ac6456c75edae9fe9d9b6938142a065b to your computer and use it in GitHub Desktop.
Call a listener once the given stylesheets have loaded
const styles = require('./styles')
const promise = styles.onLoad('foo.css', 'bar.css')

promise.then(() => {
  console.log('Stylesheets loaded!')
  // Now, measurements can be done safely!
})

Note that the strings passed to onLoad can be fragments of the stylesheet's full URL. This means foo.css will match any stylesheet whose href contains foo.css.

exports.onLoad = function() {
const loading = new Set
for (let i = 0; i < arguments.length; i++) {
const string = arguments[i]
if (typeof string == 'string') {
loading.add(string)
}
}
const sheets = document.styleSheets
function check(string) {
for (let i = 0; i < sheets.length; i++) {
const href = sheets[i].href
if (href && ~href.indexOf(string)) {
return loading.delete(string)
}
}
}
// Check immediately.
if (sheets.length) {
loading.forEach(check)
if (loading.size == 0) {
return Promise.resolve()
}
}
return new Promise(function(resolve) {
perFrame(function() {
if (sheets.length) {
loading.forEach(check)
if (loading.size == 0) {
resolve()
return false
}
}
return true
})
})
}
function perFrame(callback) {
requestAnimationFrame(function next() {
if (callback()) requestAnimationFrame(next)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment