Allow specifying external resources (#1318)

* Allow specifying external resources

* Lint
This commit is contained in:
Paulus Schoutsen 2018-06-21 17:14:25 -04:00 committed by GitHub
parent 1f82934c93
commit 501033df15
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 2 deletions

View File

@ -1,7 +1,7 @@
// Load a resource and get a promise when loading done.
// From: https://davidwalsh.name/javascript-loader
function _load(tag, url) {
function _load(tag, url, type) {
// This promise will be used by Promise.all to determine success or failure
return new Promise(function (resolve, reject) {
const element = document.createElement(tag);
@ -16,6 +16,9 @@ function _load(tag, url) {
switch (tag) {
case 'script':
element.async = true;
if (type) {
element.type = type;
}
break;
case 'link':
element.type = 'text/css';
@ -33,3 +36,4 @@ function _load(tag, url) {
export const loadCSS = url => _load('link', url);
export const loadJS = url => _load('script', url);
export const loadImg = url => _load('img', url);
export const loadModule = url => _load('script', url, 'module');

View File

@ -11,8 +11,12 @@ import { PolymerElement } from '@polymer/polymer/polymer-element.js';
import EventsMixin from '../../mixins/events-mixin.js';
import '../../layouts/ha-app-layout.js';
import { loadModule, loadJS } from '../../common/dom/load_resource.js';
import './hui-view.js';
// JS should only be imported once. Modules and HTML are safe.
const JS_CACHE = {};
class HUIRoot extends EventsMixin(PolymerElement) {
static get template() {
return html`
@ -138,7 +142,8 @@ class HUIRoot extends EventsMixin(PolymerElement) {
this.$.view.lastChild.hass = hass;
}
_configChanged() {
_configChanged(config) {
this._loadResources(config.resources);
// On config change, recreate the view from scratch.
this._selectView(this._curView);
}
@ -148,6 +153,29 @@ class HUIRoot extends EventsMixin(PolymerElement) {
this.$.view.lastChild.columns = columns;
}
_loadResources(resources) {
resources.forEach((resource) => {
switch (resource.type) {
case 'js':
if (resource.url in JS_CACHE) break;
JS_CACHE[resource.url] = loadJS(resource.url);
break;
case 'module':
loadModule(resource.url);
break;
case 'html':
import(/* webpackChunkName: "import-href-polyfill" */ '../../resources/html-import/import-href.js')
.then(({ importHref }) => importHref(resource.url));
break;
default:
// eslint-disable-next-line
console.warn('Unknown resource type specified: ${resource.type}');
}
});
}
/**
* Scroll to a specific y coordinate.