0
0
Fork 1
Spiegel von https://github.com/paviliondev/discourse-custom-wizard.git synchronisiert 2024-11-27 03:20:27 +01:00
discourse-custom-wizard/assets/javascripts/wizard/lib/load-script.js.es6

110 Zeilen
2,5 KiB
Text

import { ajax } from "./ajax";
import getURL, { getURLWithCDN } from "discourse-common/lib/get-url";
import { run } from "@ember/runloop";
import { Promise } from "rsvp";
2020-07-06 21:05:15 +02:00
2018-02-08 05:30:55 +01:00
const _loaded = {};
const _loading = {};
function loadWithTag(path, cb) {
const head = document.getElementsByTagName("head")[0];
2018-02-08 05:30:55 +01:00
let finished = false;
let s = document.createElement("script");
2018-02-08 05:30:55 +01:00
s.src = path;
if (Ember.Test) {
Ember.Test.registerWaiter(() => finished);
}
head.appendChild(s);
s.onload = s.onreadystatechange = function (_, abort) {
2018-02-08 05:30:55 +01:00
finished = true;
if (
abort ||
!s.readyState ||
s.readyState === "loaded" ||
s.readyState === "complete"
) {
2018-02-08 05:30:55 +01:00
s = s.onload = s.onreadystatechange = null;
if (!abort) {
run(null, cb);
2018-02-08 05:30:55 +01:00
}
}
};
}
export function loadCSS(url) {
return loadScript(url, { css: true });
}
export default function loadScript(url, opts) {
// TODO: Remove this once plugins have been updated not to use it:
if (url === "defer/html-sanitizer-bundle") {
return Promise.resolve();
}
2018-02-08 05:30:55 +01:00
opts = opts || {};
$("script").each((i, tag) => {
const src = tag.getAttribute("src");
2018-02-08 05:30:55 +01:00
if (src && (opts.scriptTag || src !== url)) {
_loaded[tag.getAttribute("src")] = true;
2018-02-08 05:30:55 +01:00
}
});
return new Promise(function (resolve) {
2020-07-06 21:05:15 +02:00
url = getURL(url);
2018-02-08 05:30:55 +01:00
// If we already loaded this url
if (_loaded[url]) {
return resolve();
}
if (_loading[url]) {
return _loading[url].then(resolve);
}
2018-02-08 05:30:55 +01:00
let done;
_loading[url] = new Promise(function (_done) {
2018-02-08 05:30:55 +01:00
done = _done;
});
_loading[url].then(function () {
2018-02-08 05:30:55 +01:00
delete _loading[url];
});
const cb = function (data) {
2018-02-08 05:30:55 +01:00
if (opts && opts.css) {
$("head").append("<style>" + data + "</style>");
}
done();
resolve();
_loaded[url] = true;
};
let cdnUrl = url;
// Scripts should always load from CDN
// CSS is type text, to accept it from a CDN we would need to handle CORS
if (!opts.css) {
cdnUrl = getURLWithCDN(url);
2018-02-08 05:30:55 +01:00
}
// Some javascript depends on the path of where it is loaded (ace editor)
// to dynamically load more JS. In that case, add the `scriptTag: true`
// option.
if (opts.scriptTag) {
if (Ember.testing) {
throw `In test mode scripts cannot be loaded async ${cdnUrl}`;
}
loadWithTag(cdnUrl, cb);
} else {
ajax({
url: cdnUrl,
dataType: opts.css ? "text" : "script",
cache: true,
}).then(cb);
2018-02-08 05:30:55 +01:00
}
});
}