1
0
Fork 0
mirror of https://github.com/TryGhost/Ghost-Admin.git synced 2023-12-14 02:33:04 +01:00
Ghost-Admin/app/services/lazy-loader.js
Austin Burdine 666a3e7f1a lazy-load codemirror on code injection screen (#99)
refs TryGhost/Ghost#6149
- concats codemirror.js and css on build, keeping them out of vendor.js
- add lazy-loader service to enable loading of external scripts
2016-07-05 17:30:14 +01:00

53 lines
1.4 KiB
JavaScript

import $ from 'jquery';
import Ember from 'ember';
import RSVP from 'rsvp';
import Service from 'ember-service';
import injectService from 'ember-service/inject';
const {testing} = Ember;
export default Service.extend({
ajax: injectService(),
ghostPaths: injectService(),
// This is needed so we can disable it in unit tests
testing,
scriptPromises: {},
loadScript(key, url) {
if (this.get('testing')) {
return RSVP.resolve();
}
if (this.get(`scriptPromises.${key}`)) {
// Script is already loaded/in the process of being loaded,
// so return that promise
return this.get(`scriptPromises.${key}`);
}
let ajax = this.get('ajax');
let adminRoot = this.get('ghostPaths.adminRoot');
let scriptPromise = ajax.request(`${adminRoot}${url}`, {
dataType: 'script',
cache: true
});
this.set(`scriptPromises.${key}`, scriptPromise);
return scriptPromise;
},
loadStyle(key, url) {
if (this.get('testing')) {
return RSVP.resolve();
}
if (!$(`#${key}-styles`).length) {
let $style = $(`<link rel="stylesheet" id="${key}-styles" />`);
$style.attr('href', `${this.get('ghostPaths.adminRoot')}${url}`);
$('head').append($style);
}
}
});