Skip to content

Instantly share code, notes, and snippets.

@hallettj
Created May 18, 2010 16:14
Show Gist options
  • Save hallettj/405172 to your computer and use it in GitHub Desktop.
Save hallettj/405172 to your computer and use it in GitHub Desktop.
/**
* CSS addon for Kongregate Asynchronous JavaScript Loader
*
* Adds support to KJS for loading CSS files.
*
* You can find KJS at:
* https://gist.github.com/388e70bccd3fdb8a6617
*
* Usage:
*
* kjs.loadCss('styles.css'); // loads stylesheet
* kjs.load('ui.js', [ 'styles.css' ]); // loads javascript after
* // stylesheet is fully loaded
*/
KJS.prototype.loadCSS = function(file, depends, satisfies) {
var kjs = this,
satisfy = function(s) {
return function(body) {
kjs.embedCSS(body);
for (var i = s.length - 1; i >= 0; i--) { kjs.sat(s[i]); }
};
}((satisfies || []).concat(file.split('?')[0]));
this.get(this._path + file, function(body) {
depends && depends.length ?
kjs.run(function() { satisfy(body); }, depends) :
satisfy(body);
});
}
KJS.prototype.embedCSS = function(body) {
var s = document.createElement('style');
document.getElementsByTagName('head')[0].appendChild(s);
s.innerHTML = body;
};
function testEmbedCSS() {
var kjs = new KJS(),
styles = 'p { color: #111 }';
kjs.embedCSS(styles);
assertEquals("Expected style tag to have been appended to document head with provided body",
styles, document.getElementsByTagName('head')[0].lastChild.innerHTML);
}
function testLoadCSSWithSatisfies() {
var kjs = new KJS();
kjs.get = function(url, fn) { fn("contents of " + url); };
kjs.embedCSS = function() {};
var has_been_run = false;
kjs.run(function() { has_been_run = true; }, [ '/a.js' ]);
kjs.loadCSS('/bundle.js', [], [ '/a.js' ]);
assertTrue("Expected callback with virtual dependencies to have been satisfied", has_been_run);
}
@duncanbeevers
Copy link

Nice.
From EFWS:

stylesheets followed by an inline script block any subsequent resources from downloading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment