Skip to content

Instantly share code, notes, and snippets.

@leandrowd
Last active August 29, 2015 14:15
Show Gist options
  • Select an option

  • Save leandrowd/023d4c3f06839a8ada75 to your computer and use it in GitHub Desktop.

Select an option

Save leandrowd/023d4c3f06839a8ada75 to your computer and use it in GitHub Desktop.
WaitFor
module.exports = function(file, title) {
var cssFile = document.createElement("link");
cssFile.setAttribute("rel", "stylesheet")
cssFile.setAttribute("type", "text/css")
cssFile.setAttribute("href", file);
cssFile.setAttribute("title", title);
document.getElementsByTagName("head")[0].appendChild(cssFile);
}
/**
* Example 1:
*
* You are creating a snippet js to be embeddedon a 3rd party website, which also import the css.
* Some function needs to calculate space, so it should wait for the css before
* performing the calculations. There is no cross browser load method for
* detecting when the css is loaded and you are not using any ajax loader
* for your files.
*/
var waitFor = require('./waitFor');
var isCssLoaded = require('./isCssLoaded');
var appendCss = require('./appendCss');
// adding css
appendCss('http://ex.com/file.css', 'myCss');
// waiting until the method `isCssLoaded`using the attributes `['myCss']``
// returns `true` to execute the `myCallback()`
waitFor(isCssLoaded, ['myCss'], function myCallback () {
// run your css dependent method now
console.log("My css is loaded");
})
module.exports = function(title){
// recover all loaded stylesheets
var loadedCss = document.styleSheets;
// filter by title (yeah, you should add a title to your css in order to make easier handle it)
var targetCss = Array.prototype.slice.call(loadedCss).filter(function(item){
return item.title === title;
});
// if your css was found, returns true
return targetCss.length > 0;
}
/**
* waitFor - If you need to wait a given condition before execute something
* and you there is no native crossbrowser api to do. This method can help!
*
* @param test [function|bool] the object or function to be tested
* @param attributes [array] testing attributes to be sent to the test function
* @param callbac [function] action to be executed when the condition is true
* @param interval [number] miliseconds between each test (optional)
*/
module.exports = function (test, attributes, callback, interval) {
var isFunction = (typeof test === 'function');
var loop = function (test) {
if (isFunction && test.apply(null, attributes) || test) {
return callback();
}
setTimeout(loop, interval || 100);
}.bind(null, test)
loop(test);
}
module.exports = waitFor;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment