comparison 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
comparison
equal deleted inserted replaced
28:d796bbbe558c 29:acdcdf1a8d21
1 define(["../Deferred", "../log/trace!"], function (Deferred, trace) {
2 function on(node, eventName, handler) {
3 // Add an event listener to a DOM node
4 node.addEventListener(eventName, handler, false);
5
6 return function () {
7 node.removeEventListener(eventName, handler, false);
8 };
9 }
10
11 return {
12 injectionPoint: document.head,
13 injectBefore: document.head.firstChild,
14
15 _map: {},
16
17 _inject: function (name, attr) {
18 var node = document.createElement(name),
19 d = new Deferred(),
20
21 cleanup = function () {
22 noerr();
23 noload();
24 },
25
26 noload = on(node, "load", function () {
27 d.resolve({
28 node: node
29 });
30 cleanup();
31 }, true),
32
33 noerr = on(node, "error", function (e) {
34 d.reject({
35 erorr: e,
36 node: node
37 });
38 cleanup();
39 }, true);
40
41 for (var p in attr)
42 node[p] = attr[p];
43
44 this.injectionPoint.insertBefore(node, this.injectBefore);
45 return d;
46 },
47
48 injectScript: function (url) {
49 var d = this._map[url];
50 if (!d) {
51 trace.log("js {0}", url);
52 d = this._inject("script", {
53 type: "text/javascript",
54 charset: "utf-8",
55 src: url
56 });
57 d.then(function () {
58 trace.log("done {0}", url);
59 }, function (e) {
60 trace.err([url, e]);
61 });
62 this._map[url] = d;
63 }
64 return d;
65 },
66
67 injectStylesheet: function (url) {
68 var d = this._map[url];
69 if (!d) {
70 trace.log("css {0}", url);
71 d = this._inject("link", {
72 type: "text/css",
73 rel: "stylesheet",
74 href: url
75 });
76 d.then(function () {
77 trace.log("done {0}", url);
78 }, function (e) {
79 trace.error([url, e]);
80 });
81 this._map[url] = d;
82 }
83 return d;
84 }
85 };
86 });