Christophe Dervieux | e1893ae | 2021-10-07 17:09:02 +0200 | [diff] [blame] | 1 | /** |
| 2 | * Loads a JavaScript file from the given URL and executes it. |
| 3 | * |
| 4 | * @param {string} url Address of the .js file to load |
| 5 | * @param {function} callback Method to invoke when the script |
| 6 | * has loaded and executed |
| 7 | */ |
| 8 | export const loadScript = ( url, callback ) => { |
| 9 | |
| 10 | const script = document.createElement( 'script' ); |
| 11 | script.type = 'text/javascript'; |
| 12 | script.async = false; |
| 13 | script.defer = false; |
| 14 | script.src = url; |
| 15 | |
| 16 | if( typeof callback === 'function' ) { |
| 17 | |
| 18 | // Success callback |
| 19 | script.onload = script.onreadystatechange = event => { |
| 20 | if( event.type === 'load' || /loaded|complete/.test( script.readyState ) ) { |
| 21 | |
| 22 | // Kill event listeners |
| 23 | script.onload = script.onreadystatechange = script.onerror = null; |
| 24 | |
| 25 | callback(); |
| 26 | |
| 27 | } |
| 28 | }; |
| 29 | |
| 30 | // Error callback |
| 31 | script.onerror = err => { |
| 32 | |
| 33 | // Kill event listeners |
| 34 | script.onload = script.onreadystatechange = script.onerror = null; |
| 35 | |
| 36 | callback( new Error( 'Failed loading script: ' + script.src + '\n' + err ) ); |
| 37 | |
| 38 | }; |
| 39 | |
| 40 | } |
| 41 | |
| 42 | // Append the script at the end of <head> |
| 43 | const head = document.querySelector( 'head' ); |
| 44 | head.insertBefore( script, head.lastChild ); |
| 45 | |
| 46 | } |