Created
September 20, 2019 08:17
-
-
Save ElManouche/24ffae9bd50024c9011fdda530c23e04 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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