# HG changeset patch # User cin # Date 1512696703 -10800 # Node ID c2a7d21175cea3272d1207f4e1b20da0d08f0b0b # Parent f750c89976d34ab749e9a6bb978363e30a622be3 Added css injection plugin, implab/dom/css! diff -r f750c89976d3 -r c2a7d21175ce src/implab/dom/css.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/implab/dom/css.js Fri Dec 08 04:31:43 2017 +0300 @@ -0,0 +1,10 @@ +define(["./inject"], function (inject) { + return { + load: function (id, require, cb) { + var url = require.toUrl(id); + inject.injectStylesheet(url).then(function () { + cb(); + }); + } + }; +}); \ No newline at end of file diff -r f750c89976d3 -r c2a7d21175ce src/implab/dom/inject.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/implab/dom/inject.js Fri Dec 08 04:31:43 2017 +0300 @@ -0,0 +1,86 @@ +define(["../Deferred", "../log/trace!"], function (Deferred, trace) { + function on(node, eventName, handler) { + // Add an event listener to a DOM node + node.addEventListener(eventName, handler, false); + + return function () { + node.removeEventListener(eventName, handler, false); + }; + } + + return { + injectionPoint: document.head, + injectBefore: document.head.firstChild, + + _map: {}, + + _inject: function (name, attr) { + var node = document.createElement(name), + d = new Deferred(), + + cleanup = function () { + noerr(); + noload(); + }, + + noload = on(node, "load", function () { + d.resolve({ + node: node + }); + cleanup(); + }, true), + + noerr = on(node, "error", function (e) { + d.reject({ + erorr: e, + node: node + }); + cleanup(); + }, true); + + for (var p in attr) + node[p] = attr[p]; + + this.injectionPoint.insertBefore(node, this.injectBefore); + return d; + }, + + injectScript: function (url) { + var d = this._map[url]; + if (!d) { + trace.log("js {0}", url); + d = this._inject("script", { + type: "text/javascript", + charset: "utf-8", + src: url + }); + d.then(function () { + trace.log("done {0}", url); + }, function (e) { + trace.err([url, e]); + }); + this._map[url] = d; + } + return d; + }, + + injectStylesheet: function (url) { + var d = this._map[url]; + if (!d) { + trace.log("css {0}", url); + d = this._inject("link", { + type: "text/css", + rel: "stylesheet", + href: url + }); + d.then(function () { + trace.log("done {0}", url); + }, function (e) { + trace.error([url, e]); + }); + this._map[url] = d; + } + return d; + } + }; +}); \ No newline at end of file