один .js для загрузки всех .js и .css - PullRequest
0 голосов
/ 08 октября 2011

Мне нужно создать простой тип встраивания 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>

Мне также необходимо иметь возможность работать на нескольких версияхта же страница.

Идентификатор (например, 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 отсортировать все это только с помощью одного связанного скрипта и небольшой функции на странице.

Что я написалдо сих пор не работает, потому что функция пытается работать до загрузки зависимостей.

Любая помощь в этом вопросе приветствуется.

Ответы [ 2 ]

2 голосов
/ 08 октября 2011

Пусть это будет ваш загруженный скрипт (настройте первый блок в соответствии с вашими пожеланиями).По запросу 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>
2 голосов
/ 08 октября 2011

Вы пытались использовать document.write (), чтобы вставить новые теги <script> и <style> на страницу для загрузки своих ресурсов?

...