Dynamically load a JavaScript file

后端 未结 28 3021
说谎
说谎 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:51

    I did basically the same thing that you did Adam, but with a slight modification to make sure I was appending to the head tag to get the job done. I simply created an include function (code below) to handle both script and css files.

    This function also checks to make sure that the script or CSS file hasn't already been loaded dynamically. It does not check for hand coded values and there may have been a better way to do that, but it served the purpose.

    function include( url, type ){
        // First make sure it hasn't been loaded by something else.
        if( Array.contains( includedFile, url ) )
            return;
    
        // Determine the MIME-type
        var jsExpr = new RegExp( "js$", "i" );
        var cssExpr = new RegExp( "css$", "i" );
        if( type == null )
            if( jsExpr.test( url ) )
                type = 'text/javascript';
            else if( cssExpr.test( url ) )
                type = 'text/css';
    
        // Create the appropriate element.
        var tag = null;
        switch( type ){
            case 'text/javascript' :
                tag = document.createElement( 'script' );
                tag.type = type;
                tag.src = url;
                break;
            case 'text/css' :
                tag = document.createElement( 'link' );
                tag.rel = 'stylesheet';
                tag.type = type;
                tag.href = url;
                break;
        }
    
        // Insert it to the  and the array to ensure it is not
        // loaded again.
        document.getElementsByTagName("head")[0].appendChild( tag );
        Array.add( includedFile, url );
    }
    

提交回复
热议问题