diff --git a/src/common/dom/load_resource.js b/src/common/dom/load_resource.js index eefcfc627e..618a2882af 100644 --- a/src/common/dom/load_resource.js +++ b/src/common/dom/load_resource.js @@ -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'); diff --git a/src/panels/lovelace/hui-root.js b/src/panels/lovelace/hui-root.js index f57543d920..84bfc6018a 100644 --- a/src/panels/lovelace/hui-root.js +++ b/src/panels/lovelace/hui-root.js @@ -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.