Sascha Schulz
2024-06-10 1838ab5ce4d049d6c113124b1969dfebc90b4163
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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 );
 
}