Skip to content

Instantly share code, notes, and snippets.

@JoxieMedina
Forked from jtpaasch/loader.js
Last active August 10, 2018 01:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoxieMedina/915bcaee0b582663e8275fb660b52ea7 to your computer and use it in GitHub Desktop.
Save JoxieMedina/915bcaee0b582663e8275fb660b52ea7 to your computer and use it in GitHub Desktop.
Javascript module for loading scripts asynchronously.
import {uniqueId} from 'lodash' // optional
/**
* @param {String} file The path of the file you want to load.
* @param {Function} callback (optional) The function to call when the script loads.
* @param {String} id (optional) The unique id of the file you want to load.
*/
export const loadAsyncScript = (file, callback, id) => {
const d = document
if (!id) { id = uniqueId('async_script') } // optional
if (!d.getElementById(id)) {
const tag = 'script'
let newScript = d.createElement(tag)
let firstScript = d.getElementsByTagName(tag)[0]
newScript.id = id
newScript.async = true
newScript.src = file
if (callback) {
// IE support
newScript.onreadystatechange = () => {
if (newScript.readyState === 'loaded' || newScript.readyState === 'complete') {
newScript.onreadystatechange = null
callback(file)
}
}
// Other (non-IE) browsers support
newScript.onload = () => {
callback(file)
}
}
firstScript.parentNode.insertBefore(newScript, firstScript)
} else {
console.error(`The script with id ${id} is already loaded`)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment