JavaScript动态加载资源

    //动态加载样式
    function dynamicLoadingCss(path){
        if(!path || path.length === 0){
            return false;
        }
        var head = document.getElementsByTagName('head')[0];
        var link = document.createElement('link');
        link.href = path;
        link.rel = 'stylesheet';
        link.type = 'text/css';
        head.appendChild(link);
    }

    //动态加载脚本
    function dynamicLoadingScript(path,callback){
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.src = path;
        script.type = 'text/javascript';
        if (typeof callback === "function") {
            script.onload= function(){
                callback();
            }
        }
        head.appendChild(script);
    }

  使用方式

   //加载bootstrap的时间选择器
    function GetDateTimePicker(){
        dynamicLoadingCss("/Content/css/bootstrap.css");
        dynamicLoadingCss("/Content/css/datetimepicker/bootstrap-datetimepicker.min.css");

        dynamicLoadingScript("/Scripts/bootstrap.js","");
        dynamicLoadingScript("/Scripts/datetimepicker/bootstrap-datetimepicker.min.js",function(){
            dynamicLoadingScript("/Scripts/datetimepicker/locales/bootstrap-datetimepicker.zh-CN.js","");
            dynamicLoadingScript("/Scripts/hex-datetimepicker.js","");
        });
    }

 

posted @ 2016-04-24 11:01  寂寞之砂  阅读(1180)  评论(0编辑  收藏  举报