Dynamically loading JavaScript synchronously

后端 未结 18 2294
小蘑菇
小蘑菇 2020-11-27 13:55

I\'m using the module pattern, one of the things I want to do is dynamically include an external JavaScript file, execute the file, and then use the functions/variables in t

18条回答
  •  Happy的楠姐
    2020-11-27 14:33

    My strategy, classic example when load jQuery UI, i hope this can help you

    ( function( tools, libs ){
    	
        // Iterator
        var require = function( scripts, onEnd ){
            
            onEnd = onEnd || function(){};
            
            if( !scripts || scripts.length < 1 )return onEnd();
            
            var src    = scripts.splice( 0, 1),
                script = document.createElement( "script" );
            
            script.setAttribute( "src", src );
            
            tools.addEvent( "load", script, function(){
                
                require( scripts, onEnd );
                
            } );
            
            document.getElementsByTagName( "head" )[ 0 ].appendChild( script );
            
        };
        
        // Install all scripts with a copy of scripts
        require( libs.slice(), function(){
        
            alert( "Enjoy :)" );
        
        } );
        
        // Timeout information
        var ti = setTimeout( function(){
            
            if( !window.jQuery || !window.jQuery.ui )alert( "Timeout !" );
            
            clearTimeout( ti );
            
        }, 5000 );
    
    } )(
    
        { // Tools
        
            addEvent : function( evnt, elem, func ){
            
                try{
    
                    if( elem.addEventListener ){
    
                        elem.addEventListener( evnt, func, false );
    
                    }else if( elem.attachEvent ){
    
                         var r = elem.attachEvent( "on" + evnt, func );
    
                    }
    
                    return true;
    
                }catch( e ){
    
                    return false;
    
                }		    
    
            }
        
        },
        [ // Scripts
        
            "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js",
            "https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"
            
        ]
    
    );

提交回复
热议问题