-
-
Save JoxieMedina/915bcaee0b582663e8275fb660b52ea7 to your computer and use it in GitHub Desktop.
Javascript module for loading scripts asynchronously.
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
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