Skip to content

Instantly share code, notes, and snippets.

@ElManouche
Created September 20, 2019 08:17
Show Gist options
  • Save ElManouche/24ffae9bd50024c9011fdda530c23e04 to your computer and use it in GitHub Desktop.
Save ElManouche/24ffae9bd50024c9011fdda530c23e04 to your computer and use it in GitHub Desktop.
const loadingState = {
PENDING: 'pending',
LOADED: 'loaded',
FAILED: 'failed'
};
const delay = t => new Promise(resolve => setTimeout(resolve, t));
/**
Loads a resource using a promise, can call then after
Ex: ResourceUtils.load(url, options).then(this.someInitFunction);
url: the url of the resource
options:
parentTag: the destination of the tag to add (default document.body)
*/
const load = (url, options = {}) => {
const {
parentTag,
...otherOptions
} = options;
return new Promise((resolve, reject) => {
if (!window.loadedResources) {
window.loadedResources = [];
}
if (!window.loadedResources[url]) {
window.loadedResources[url] = loadingState.PENDING;
const tag = getTag(url, otherOptions);
(parentTag || document.body).appendChild(tag);
tag.addEventListener('load', () => {
window.loadedResources[url] = loadingState.LOADED;
resolve();
});
tag.addEventListener('error', () => {
window.loadedResources[url] = loadingState.FAILED;
reject();
});
} else {
const checkResource = () => {
if (window.loadedResources[url] === loadingState.LOADED) {
resolve();
} else if (window.loadedResources[url] === loadingState.FAILED) {
reject();
}
};
checkResource();
for (let i=1; i<10; i++) {
delay(i*500).then(checkResource);
}
}
});
};
const getTag = (url, options = {}) => {
const fileType = getFileType(url);
let tag;
if (fileType === 'stylesheet') {
tag = document.createElement('link');
tag.setAttribute('href', url);
tag.setAttribute('rel', fileType);
} else {
tag = document.createElement('script');
tag.setAttribute('src', url);
if (options.tagAttributes) {
Object.keys(options.tagAttributes).forEach((key, _index) => {
tag.setAttribute(key, options[key]);
});
}
}
return tag;
};
const getFileType = (url) => {
switch (StringUtils.getFileExtension(url)) {
case 'css': return 'stylesheet';
case 'js': return 'script';
}
};
export default {
load
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment