diff --git a/css.js b/css.js index 26b637c..34ff605 100644 --- a/css.js +++ b/css.js @@ -118,8 +118,7 @@ CSSModule.prototype = { // * Zombie headless browser // Weak inference targets Android < 4.4 and // a fallback for IE 8 and beneath - if( "isApplicationInstalled" in navigator || - !link.addEventListener) { + if("isApplicationInstalled" in navigator || !link.addEventListener) { // fallback, polling styleSheets onloadCss(link, loadCB); } else if(navigator.noUI){ @@ -282,3 +281,4 @@ exports.getHead = getHead; exports.locateScheme = true; exports.buildType = "css"; exports.includeInBuild = true; +exports.pluginBuilder = "steal-css/slim"; diff --git a/package.json b/package.json index 016aa16..fa537c6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "steal-css", - "version": "1.2.5", + "version": "1.2.6", "description": "CSS plugin for StealJS", "main": "css.js", "scripts": { diff --git a/slim.js b/slim.js new file mode 100644 index 0000000..8d9f96c --- /dev/null +++ b/slim.js @@ -0,0 +1,67 @@ +/* naive version of the css plugin for the slim loader */ +module.exports = function(moduleId, config) { + return new CssModule(config.paths[config.bundles[moduleId]]).injectLink(); +}; + +function CssModule(address) { + this.address = address; +} + +// timeout in seconds +CssModule.waitTimeout = 60; + +CssModule.prototype.linkExists = function() { + var styleSheets = document.styleSheets; + + for (var i = 0; i < styleSheets.length; ++i) { + if (this.address === styleSheets[i].href) { + return true; + } + } + + return false; +}; + +CssModule.prototype.injectLink = function() { + if (this._loadPromise) { + return this._loadPromise; + } + + if (this.linkExists()) { + this._loadPromise = Promise.resolve(""); + return this._loadPromise; + } + + // inspired by https://github.com/filamentgroup/loadCSS + var link = (this.link = document.createElement("link")); + link.type = "text/css"; + link.rel = "stylesheet"; + link.href = this.address; + + // wait until the css file is loaded + this._loadPromise = new Promise(function(resolve, reject) { + var timeout = setTimeout(function() { + reject("Unable to load CSS"); + }, CssModule.waitTimeout * 1000); + + var linkEventCallback = function(event) { + clearTimeout(timeout); + + link.removeEventListener("load", linkEventCallback); + link.removeEventListener("error", linkEventCallback); + + if (event && event.type === "error") { + reject("Unable to load CSS"); + } else { + resolve(""); + } + }; + + link.addEventListener("load", linkEventCallback); + link.addEventListener("error", linkEventCallback); + + document.head.appendChild(link); + }); + + return this._loadPromise; +};