diff options
| author | Juan Marin Noguera <juan@mnpi.eu> | 2023-08-22 17:56:56 +0200 |
|---|---|---|
| committer | Juan Marin Noguera <juan@mnpi.eu> | 2023-08-22 17:56:56 +0200 |
| commit | 1fd2213192d22880706440e7f724bdc6db966ee0 (patch) | |
| tree | ff2d6812ef6db399852ad8c4cf2b6f1cd417dfed /present/js/utils/loader.js | |
| parent | 2f9eb7a94819a08937ba08320a142b7f0be407fd (diff) | |
Añadida presentación1.0
Diffstat (limited to 'present/js/utils/loader.js')
| -rw-r--r-- | present/js/utils/loader.js | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/present/js/utils/loader.js b/present/js/utils/loader.js new file mode 100644 index 0000000..58d39ac --- /dev/null +++ b/present/js/utils/loader.js @@ -0,0 +1,46 @@ +/** + * Loads a JavaScript file from the given URL and executes it. + * + * @param {string} url Address of the .js file to load + * @param {function} callback Method to invoke when the script + * has loaded and executed + */ +export const loadScript = ( url, callback ) => { + + const script = document.createElement( 'script' ); + script.type = 'text/javascript'; + script.async = false; + script.defer = false; + script.src = url; + + if( typeof callback === 'function' ) { + + // Success callback + script.onload = script.onreadystatechange = event => { + if( event.type === 'load' || /loaded|complete/.test( script.readyState ) ) { + + // Kill event listeners + script.onload = script.onreadystatechange = script.onerror = null; + + callback(); + + } + }; + + // Error callback + script.onerror = err => { + + // Kill event listeners + script.onload = script.onreadystatechange = script.onerror = null; + + callback( new Error( 'Failed loading script: ' + script.src + '\n' + err ) ); + + }; + + } + + // Append the script at the end of <head> + const head = document.querySelector( 'head' ); + head.insertBefore( script, head.lastChild ); + +}
\ No newline at end of file |
