Dynamically load a JavaScript file

后端 未结 28 2998
说谎
说谎 2020-11-22 06:56

How can you reliably and dynamically load a JavaScript file? This will can be used to implement a module or component that when \'initialized\' the component will dynamical

28条回答
  •  清酒与你
    2020-11-22 07:27

    Keep it nice, short, simple, and maintainable! :]

    // 3rd party plugins / script (don't forget the full path is necessary)
    var FULL_PATH = '', s =
    [
        FULL_PATH + 'plugins/script.js'      // Script example
        FULL_PATH + 'plugins/jquery.1.2.js', // jQuery Library 
        FULL_PATH + 'plugins/crypto-js/hmac-sha1.js',      // CryptoJS
        FULL_PATH + 'plugins/crypto-js/enc-base64-min.js'  // CryptoJS
    ];
    
    function load(url)
    {
        var ajax = new XMLHttpRequest();
        ajax.open('GET', url, false);
        ajax.onreadystatechange = function ()
        {
            var script = ajax.response || ajax.responseText;
            if (ajax.readyState === 4)
            {
                switch(ajax.status)
                {
                    case 200:
                        eval.apply( window, [script] );
                        console.log("library loaded: ", url);
                        break;
                    default:
                        console.log("ERROR: library not loaded: ", url);
                }
            }
        };
        ajax.send(null);
    }
    
     // initialize a single load 
    load('plugins/script.js');
    
    // initialize a full load of scripts
    if (s.length > 0)
    {
        for (i = 0; i < s.length; i++)
        {
            load(s[i]);
        }
    }
    

    This code is simply a short functional example that could require additional feature functionality for full support on any (or given) platform.

提交回复
热议问题