DEV: Clean up `loadScript()` (#16537)

This commit is contained in:
Jarek Radosz 2022-04-22 11:53:39 +02:00 committed by GitHub
parent f2f1a4df62
commit 70b69e318a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 10 additions and 10 deletions

View File

@ -47,28 +47,24 @@ export function loadCSS(url) {
return loadScript(url, { css: true }); return loadScript(url, { css: true });
} }
export default function loadScript(url, opts) { export default function loadScript(url, opts = {}) {
// TODO: Remove this once plugins have been updated not to use it: // TODO: Remove this once plugins have been updated not to use it:
if (url === "defer/html-sanitizer-bundle") { if (url === "defer/html-sanitizer-bundle") {
return Promise.resolve(); return Promise.resolve();
} }
opts = opts || {};
if (_loaded[url]) { if (_loaded[url]) {
return Promise.resolve(); return Promise.resolve();
} }
if (PUBLIC_JS_VERSIONS) {
url = cacheBuster(url); url = cacheBuster(url);
}
// Scripts should always load from CDN // Scripts should always load from CDN
// CSS is type text, to accept it from a CDN we would need to handle CORS // CSS is type text, to accept it from a CDN we would need to handle CORS
const fullUrl = opts.css ? getURL(url) : getURLWithCDN(url); const fullUrl = opts.css ? getURL(url) : getURLWithCDN(url);
$("script").each((i, tag) => { document.querySelectorAll("script").forEach((element) => {
const src = tag.getAttribute("src"); const src = element.getAttribute("src");
if (src && src !== fullUrl && !_loading[src]) { if (src && src !== fullUrl && !_loading[src]) {
_loaded[src] = true; _loaded[src] = true;
@ -80,6 +76,7 @@ export default function loadScript(url, opts) {
if (_loaded[fullUrl]) { if (_loaded[fullUrl]) {
return resolve(); return resolve();
} }
if (_loading[fullUrl]) { if (_loading[fullUrl]) {
return _loading[fullUrl].then(resolve); return _loading[fullUrl].then(resolve);
} }
@ -94,9 +91,12 @@ export default function loadScript(url, opts) {
}); });
const cb = function (data) { const cb = function (data) {
if (opts && opts.css) { if (opts?.css) {
$("head").append("<style>" + data + "</style>"); const style = document.createElement("style");
style.innerText = data;
document.querySelector("head").appendChild(style);
} }
done(); done();
resolve(); resolve();
_loaded[url] = true; _loaded[url] = true;