From c348174d1c433dd7fe7b68378da4b2b18266c954 Mon Sep 17 00:00:00 2001 From: Gary Katsevman Date: Thu, 25 Feb 2021 12:25:10 -0500 Subject: [PATCH] chore: use deferred scripts for faster demo startup (#1083) --- scripts/index-demo-page.js | 39 ++++++++++++++++++++++---------------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/scripts/index-demo-page.js b/scripts/index-demo-page.js index c09cb8bbe..d6b17806b 100644 --- a/scripts/index-demo-page.js +++ b/scripts/index-demo-page.js @@ -166,21 +166,6 @@ // eslint-disable-next-line var reloadScripts = function(urls, cb) { var el = document.getElementById('reload-scripts'); - var onload = function() { - var script; - - if (!urls.length) { - cb(); - return; - } - - script = document.createElement('script'); - - script.src = urls.shift(); - script.onload = onload; - - el.appendChild(script); - }; if (!el) { el = document.createElement('div'); @@ -192,7 +177,29 @@ el.removeChild(el.firstChild); } - onload(); + const loaded = []; + + function checkDone() { + if (loaded.length === urls.length) { + cb(); + } + } + + urls.forEach((url) => { + const script = document.createElement('script'); + // scripts marked as defer will be loaded asynchronously but will be executed in the order they are in the DOM + script.defer = true; + // dynamically created scripts are async by default unless otherwise specified + // async scripts are loaded asynchronously but also executed as soon as they are loaded + // we want to load them in the order they are added therefore we want to turn off async + script.async = false; + script.src = url; + script.onload = () => { + loaded.push(url); + checkDone(); + }; + el.appendChild(script); + }); }; var regenerateRepresentations = function() {