1
0
mirror of https://github.com/ascribe/onion.git synced 2024-11-15 01:25:17 +01:00
onion/js/mixins/inject_in_head_mixin.js

72 lines
1.8 KiB
JavaScript
Raw Normal View History

'use strict';
2015-05-27 17:34:15 +02:00
let mapAttr = {
link: 'href',
2015-06-05 14:14:59 +02:00
script: 'src'
};
2015-05-27 17:34:15 +02:00
2015-06-03 16:53:27 +02:00
let mapTag = {
js: 'script',
2015-05-27 17:34:15 +02:00
css: 'link'
};
2015-05-27 17:34:15 +02:00
let InjectInHeadMixin = {
/**
* Provide functions to inject `<script>` and `<link>` in `<head>`.
* Useful when you have to load a huge external library and
* you don't want to embed everything inside the build file.
*/
isPresent(tag, src) {
let attr = mapAttr[tag];
let query = `head > ${tag}[${attr}="${src}"]`;
return document.querySelector(query);
},
2015-06-05 14:14:59 +02:00
injectTag(tag, src) {
2015-06-03 16:53:27 +02:00
let promise = new Promise((resolve, reject) => {
if (InjectInHeadMixin.isPresent(tag, src)) {
resolve();
} else {
let attr = mapAttr[tag];
let element = document.createElement(tag);
2015-06-05 14:14:59 +02:00
if (tag === 'script') {
2015-06-03 16:53:27 +02:00
element.onload = () => resolve();
element.onerror = () => reject();
} else {
resolve();
}
document.head.appendChild(element);
element[attr] = src;
2015-06-05 14:14:59 +02:00
if (tag === 'link') {
element.rel = 'stylesheet';
2015-06-05 13:15:31 +02:00
}
2015-06-03 16:53:27 +02:00
}
});
2015-05-27 17:34:15 +02:00
2015-06-03 16:53:27 +02:00
return promise;
2015-05-27 17:34:15 +02:00
},
injectStylesheet(src) {
2015-06-03 16:53:27 +02:00
return InjectInHeadMixin.injectTag('link', src);
2015-05-27 17:34:15 +02:00
},
injectScript(src) {
2015-06-03 16:53:27 +02:00
return InjectInHeadMixin.injectTag('source', src);
2015-05-27 17:34:15 +02:00
},
inject(src) {
let ext = src.split('.').pop();
2015-06-03 16:53:27 +02:00
let tag = mapTag[ext];
if (!tag) {
throw new Error(`Cannot inject ${src} in the DOM, cannot guess the tag name from extension "${ext}". Valid extensions are "js" and "css".`);
2015-05-27 17:34:15 +02:00
}
2015-06-03 16:53:27 +02:00
return InjectInHeadMixin.injectTag(tag, src);
2015-05-27 17:34:15 +02:00
}
};
export default InjectInHeadMixin;