FIX: Allow `loadScript` to use script tags if the JS library require it.

This commit is contained in:
Robin Ward 2015-03-12 13:09:17 -04:00
parent 69851bc6cf
commit 3ecb58980f
2 changed files with 30 additions and 12 deletions

View File

@ -32,15 +32,7 @@ export default Ember.Component.extend({
_initEditor: function() {
const self = this;
loadScript("/javascripts/ace/ace.js").then(function() {
// this is a bit weird, unlike $LAB loadScript is not keeping
// relative directory which messes stuff up
// TODO: correct relative directory and get rid of this
_.each(["base","mode","theme","worker"], function(p){
ace.config.set(p +"Path", "/javascripts/ace");
});
loadScript("/javascripts/ace/ace.js", { scriptTag: true }).then(function() {
const editor = ace.edit(self.$('.ace')[0]);
editor.setTheme("ace/theme/chrome");

View File

@ -2,16 +2,42 @@
const _loaded = {};
export default function loadScript(url) {
function loadWithTag(path, cb) {
const head = document.getElementsByTagName('head')[0];
let s = document.createElement('script');
s.src = path;
head.appendChild(s);
s.onload = s.onreadystatechange = function(_, abort) {
if (abort || !s.readyState || s.readyState === "loaded" || s.readyState === "complete") {
s = s.onload = s.onreadystatechange = null;
if (!abort) { cb(); }
}
};
}
export default function loadScript(url, opts) {
opts = opts || {};
return new Ember.RSVP.Promise(function(resolve) {
url = Discourse.getURL((assetPath && assetPath(url)) || url);
// If we already loaded this url
if (_loaded[url]) { return resolve(); }
$.getScript(url).then(function() {
const cb = function() {
_loaded[url] = true;
resolve();
});
};
// 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) {
loadWithTag(url, cb);
} else {
$.getScript(url).then(cb);
}
});
}