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

发布于 2024-12-08 23:18:52 字数 916 浏览 0 评论 0原文

我需要创建一个简单的 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 文件仅使用一个链接脚本和页面上的一个小函数来对所有这些进行排序。

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

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

I need to create a simple javascript embed type thing where the user adds a small amount of javascript to their site and my script does the rest.

This is the sort of thing I would like to see on the user site:

Included once:

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

And this in the HTML:

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

I would also need to be able to have multiple versions running on the same page.

The id (eg: 1714581) is passed to my function along with my target div.

This issue is I need to have the one script load all the dependancies:

eg:

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

And once they are all loaded I would then be able to run my function.

If my function ran before they all loaded It naturally wouldn't work.

I tried using LazyLoad and LAB but couldn't work out how to have one JS file sort all this out with only one linkied script and a small function on the page.

What I have writen so far doesnt work becuas the function tries to run before the dependecies are loaded.

Any help with this issue is much appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

天涯离梦残月幽梦 2024-12-15 23:18:53

让它成为您加载的脚本(配置第一个块以满足您的愿望)。根据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>

Let this be your loaded script (configure the first block to meet your wishes). On request of the OP, I've also added a queue function.

Note: Add _REQUIRED_ instead of an external resource, if you want to delay loading additional scripts until the previously requests has been finished.

//@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);
    }
})();

In your HTML source:

<script src="path/to/doEverythingScript.js"></script>
...
<script>
    doThis(1714581, "#target-div");
</script>
我一向站在原地 2024-12-15 23:18:53

您是否尝试过使用 document.write() 在页面中插入新的

Have you tried using document.write() to insert new <script> and <style> tags into the page to load your resources?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文