From 78108e8d2c1b040eb21afafa0049de158797d491 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=A9ry=20Debongnie?= Date: Fri, 26 Apr 2019 12:47:25 +0200 Subject: [PATCH] [IMP] utils: add loadJS function Very useful to lazy load libraries in owl applications --- src/utils.ts | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/utils.ts b/src/utils.ts index 5f3795b4..7e23050f 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -164,4 +164,27 @@ export async function loadTemplates(url: string): Promise { let templates = await result.text(); templates = templates.replace(//g, ""); return templates; -} \ No newline at end of file +} + +const loadedScripts: { [key: string]: Promise } = {}; + +export function loadJS(url: string): Promise { + if (url in loadedScripts) { + return loadedScripts[url]; + } + const promise: Promise = new Promise(function(resolve, reject) { + const script = document.createElement("script"); + script.type = "text/javascript"; + script.src = url; + script.onload = function() { + resolve(); + }; + script.onerror = function() { + reject(`Error loading file '${url}'`); + }; + const head = document.head || document.getElementsByTagName("head")[0]; + head.appendChild(script); + }); + loadedScripts[url] = promise; + return promise; +}