diff dom/src/js/inject.js @ 29:acdcdf1a8d21

repository reorganized
author cin
date Tue, 26 Jun 2018 19:35:44 +0300
parents src/implab/dom/inject.js@c2a7d21175ce
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/dom/src/js/inject.js	Tue Jun 26 19:35:44 2018 +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