一个.js加载所有.js和.css

时间:2011-10-08 16:04:02

标签: javascript jquery html lazy-loading

我需要创建一个简单的javascript嵌入类型的东西,其中用户向他们的网站添加少量的javascript,我的脚本完成其余的工作。

我希望在用户网站上看到这种情况:

包括一次:

<script type="text/javascript" src="path/to/doEverythingScript.js"></script>

这在HTML中:

<div id="target-div">    
    <script type="text/javascript">
        doThis(1714581, "#target-div");
    </script> 
</div>

我还需要能够在同一页面上运行多个版本。

id(例如:1714581)与我的目标div一起传递给我的函数。

这个问题是我需要让一个脚本加载所有依赖项:

例如:

path/to/style1.css
path/to/style2.css
path/to/style3.css
path/to/jquery.js
path/to/script1.js
path/to/script2.js
path/to/script3.js
path/to/script4.js

一旦它们全部加载,我就可以运行我的功能了。

如果我的功能在它们全部加载之前运行它自然不起作用。

我尝试过使用LazyLoad和LAB但是无法解决如何让一个JS文件排序所有这一切只有一个链接脚本和页面上的一个小函数。

到目前为止我所写的内容并不起作用,因为该函数会在加载dependecies之前尝试运行。

非常感谢您对此问题的任何帮助。

2 个答案:

答案 0 :(得分:2)

您是否尝试过使用document.write()在页面中插入新的<script><style>标记来加载资源?

答案 1 :(得分:2)

让这成为您加载的脚本(配置第一个块以满足您的愿望)。根据OP的要求,我还添加了一个队列功能。

注意:如果要延迟加载其他脚本,直到先前的请求完成,请添加_REQUIRED_而不是外部资源。

//@author Rob W. See: http://stackoverflow.com/q/7698018#7698219

//The "real" doThis. You can define any number of arguments.
function _$doThis(a,b){

}

var rw$loader_queue = []; //Unique name, to prevent messing with the code
function doThis(){rw$loader_queue.push(arguments)}
function _doThisAll(){
    for(var i=0,len=rw$loader_queue.length; i<len; i++){
         //Function.apply: First argument = context (default window)
         // second argument = array of arguments
        _$doThis.apply(null, rw$loader_queue.shift());
    }
}
(function(){//Anonymous function = no variable leaking
    //Append the scripts.styles to the head, if existent. Otherwise, try body
    var main = document.getElementsByTagName("head")[0] || document.body;
    var _REQUIRED_ = ((new Date).getTime()*(new Date).getTime()||Math.random()).toString(36);
    /***CONFIGURATION**/
    var nocache = false; //false = allow caching

    /*Usage: initLoad("type",
                      (multidimensional) array | string,
                       optional function: called when initLoad finishes
                     ) */

    initLoad("style", [
      //'sc-player-widget/css/themes/dark-hive/jquery-ui-1.8.16.custom.css',
        'sc-player-widget/css/themes/base/jquery.ui.all.css',
        'sc-player-widget/css/themes/base/jquery.ui.selectmenu.css', 
        'sc-player-widget/css/sc-player.css',
        'sc-player-widget/colorbox/colorbox.css'
    ]);
    initLoad("script", [
        'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js',
         _REQUIRED_,
        'sc-player-widget/js/ui/jquery.ui.core.js', 
        'sc-player-widget/js/ui/jquery.ui.widget.js', 
        'sc-player-widget/js/ui/jquery.ui.position.js',
        'sc-player-widget/js/ui/jquery.ui.selectmenu.js', 
        'sc-player-widget/js/ui/jquery.ui.button.js',
        'sc-player-widget/colorbox/jquery.colorbox-min.js',
    ], _doThisAll);

    /*END OF CONFIG*/

    function initLoad(type, source, ready){
        var currentSources = source instanceof Array ? source : [source];
        var beforeRequire = 0;
        var paused = false;
        var hasFinished = false;
        var num_resources = 0;
        var load_success = 0;
        next(); //Start walking through the requested resource;

        return;
        function next(){
            if(!currentSources.length){ //End of sources
                if(typeof ready == "string") ready = window[ready];
                if(typeof ready == "function" && !hasFinished) (hasFinished=true) && ready();
                return;
            }
            var current = currentSources.shift();
            if(current === _REQUIRED_){
                if(!currentSources.length) return next();
                paused = true;
                return;
            }
            beforeRequire++;
            num_resources++;
            loadResource(type, current, finished);
            if(currentSources.length) next();
            // If length == 0, wait until the resources have finished loading
        }
        function finished(){
            load_success++;
            if(!--beforeRequire && paused) next();
            else if(num_resources == load_success && !currentSources.length) next();
            //If end of queue, next() = ready()
        }
    }
    function loadResource(type, src, finish){
        if(nocache) src += "?"+(new Date).getTime();
        var s = document.createElement(type=="style"?"link":type);
        var executed = false;
        function oncomplete(){
            if(executed) return;
            executed = true;
            s.onreadystatechange = s.onload = null;
            finish();
        }
        s.onreadystatechange = function(){
            if(this.readyState == "loaded" || this.readyState == "complete") oncomplete();
        }
        s.onload = oncomplete;
        if(type == "style"){
            s.type = "text/css";
            s.rel = "stylesheet";
            s.href = src;
        } else s.src = src;
        main.appendChild(s);
    }
})();

在您的HTML源代码中:

<script src="path/to/doEverythingScript.js"></script>
...
<script>
    doThis(1714581, "#target-div");
</script>