2015-06-05 11:06:36 +02:00
|
|
|
'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-06-05 11:06:36 +02:00
|
|
|
};
|
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-06-05 11:06:36 +02:00
|
|
|
};
|
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];
|
2015-06-05 13:18:16 +02:00
|
|
|
if (!tag) {
|
2015-06-02 14:00:47 +02:00
|
|
|
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;
|