如何通过 JavaScript 文件将所有 JavaScript 文件包含在目录中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4175008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:15:16  来源:igfitidea点击:

How can I include all JavaScript files in a directory via JavaScript file?

javascriptjquerygetscript

提问by Hristo

I have a bunch of JavaScript files that I would like to include in the page, but I don't want to have to keep writing

我有一堆 JavaScript 文件想要包含在页面中,但我不想继续写

<script type="text/javascript" src="js/file.js"></script>

So is there a way to include all files in a directory (unknown size)? Can I do something like...

那么有没有办法将所有文件都包含在一个目录中(未知大小)?我可以做类似...

$.getScript("js/*.js");

... to get all the JavaScript files in the "js" directory? How can I do this using jQuery?

...获取“js”目录中的所有JavaScript文件?我如何使用 jQuery 做到这一点?

采纳答案by Mark Bessey

In general, this is probably not a great idea, since your html file should only be loading JS files that they actually make use of. Regardless, this would be trivial to do with any server-side scripting language. Just insert the script tags before serving the pages to the client.

一般来说,这可能不是一个好主意,因为您的 html 文件应该只加载它们实际使用的 JS 文件。无论如何,这对于任何服务器端脚本语言来说都是微不足道的。只需在将页面提供给客户端之前插入脚本标签。

If you want to do it without using server-side scripting, you could drop your JS files into a directory that allows listing the directory contents, and then use XMLHttpRequest to read the contents of the directory, and parse out the file names and load them.

如果你想不使用服务器端脚本来做到这一点,你可以将你的 JS 文件放到一个允许列出目录内容的目录中,然后使用 XMLHttpRequest 读取目录的内容,并解析出文件名并加载它们.

Option #3 is to have a "loader" JS file that uses getScript() to load all of the other files. Put that in a script tag in all of your html files, and then you just need to update the loader file whenever you upload a new script.

选项#3 是使用 getScript() 加载所有其他文件的“加载器”JS 文件。把它放在所有 html 文件的脚本标签中,然后你只需要在上传新脚本时更新加载器文件。

回答by jellyfishtree

What about using a server-side script to generate the script tag lines? Crudely, something like this (PHP) -

使用服务器端脚本生成脚本标记行怎么样?粗略地说,像这样(PHP) -

$handle = opendir("scripts/");

while (($file = readdir($handle))!== false) {
    echo '<script type="text/javascript" src="' . $file . '"></script>';
}

closedir($handle);

回答by rob

Given that you want a 100% client side solution, in theory you could probably do this:

鉴于您想要一个 100% 的客户端解决方案,理论上您可以这样做:

Via XmlHttpRequest, get the directory listing page for that directory (most web servers return a listing of files if there is no index.html file in the directory).

通过 XmlHttpRequest,获取该目录的目录列表页面(如果目录中没有 index.html 文件,大多数 Web 服务器会返回文件列表)。

Parse that file with javascript, pulling out all the .js files. This will of course be sensitive to the format of the directory listing on your web server / web host.

使用 javascript 解析该文件,提取所有 .js 文件。这当然会对您的网络服务器/网络主机上的目录列表格式敏感。

Add the script tags dynamically, with something like this:

动态添加脚本标签,如下所示:

function loadScript (dir, file) {
 var scr = document.createElement("script");
 scr.src = dir + file;
 document.body.appendChild(scr);
 }

回答by yurin

It can be done fully client side, but all javascript file names must be specified. For example, as array items:

它可以完全在客户端完成,但必须指定所有 javascript 文件名。例如,作为数组项:

function loadScripts(){
   var directory = 'script/';
   var extension = '.js';
   var files = ['model', 'view', 'controller'];  
   for (var file of files){ 
       var path = directory + file + extension; 
       var script = document.createElement("script");
       script.src = path;
       document.body.appendChild(script);
   } 
 }

回答by bwest87

You could use something like Grunt Include Source. It gives you a nice syntax that preprocesses your HTML, and then includes whatever you want. This also means, if you set up your build tasks correctly, you can have all these includes in dev mode, but not in prod mode, which is pretty cool.

你可以使用类似Grunt Include Source 的东西。它为您提供了一个很好的语法,可以预处理您的 HTML,然后包含您想要的任何内容。这也意味着,如果你正确设置了你的构建任务,你可以在开发模式下包含所有这些,但不能在生产模式下,这很酷。

If you aren't using Grunt for your project, there's probably similar tools for Gulp, or other task runners.

如果你的项目没有使用 Grunt,那么 Gulp 或其他任务运行器可能有类似的工具。

回答by Alberto Martinez

You can't do that in JavaScript, since JS is executed in the browser, not in the server, so it didn't know anything about directories or other server resources.

你不能在 JavaScript 中这样做,因为 JS 是在浏览器中执行的,而不是在服务器中,所以它对目录或其他服务器资源一无所知。

The best option is using a server side script like the one posted by jellyfishtree.

最好的选择是使用服务器端脚本,如 jellyfishtree 发布的脚本。

回答by Pascal

@jellyfishtree it would be a better if you create one php file which includes all your js files from the directory and then only include this php file via a script tag. This has a better performance because the browser has to do less requests to the server. See this:

javascripts.php:

@jellyfishtree 如果您创建一个包含目录中所有 js 文件的 php 文件,然后仅通过脚本标记包含此 php 文件,那就更好了。这具有更好的性能,因为浏览器对服务器的请求更少。看到这个:

javascripts.php:

<?php
   //sets the content type to javascript 
   header('Content-type: text/javascript');

   // includes all js files of the directory
   foreach(glob("packages/*.js") as $file) {
      readfile($file);
   }
?>


index.php:


索引.php:

<script type="text/javascript" src="javascripts.php"></script>

That's it!
Have fun! :)

就是这样!
玩得开心!:)

回答by Lo?c Faure-Lacroix

You can't do that in Javascript from the browser... If I were you, I would use something like browserify. Write your code using commonjs modules and then compile the javascript file into one.

你不能在浏览器的 Javascript 中做到这一点......如果我是你,我会使用像browserify这样的东西。使用 commonjs 模块编写代码,然后将 javascript 文件编译为一个。

In your html load the javascript file that you compiled.

在您的 html 中加载您编译的 javascript 文件。

回答by Frozenfrank

I was looking for an answer to this question and had my own problems. I found a couple solutions in various places and put them together into my own preferred answer.

我正在寻找这个问题的答案并且有我自己的问题。我在不同的地方找到了几个解决方案,并将它们组合成我自己喜欢的答案。

function exploreFolder(folderURL,options){
/* options:                 type            explaination

    **REQUIRED** callback:  FUNCTION        function to be called on each file. passed the complete filepath
    then:                   FUNCTION        function to be called after loading all files in folder. passed the number of files loaded
    recursive:              BOOLEAN         specifies wether or not to travel deep into folders
    ignore:                 REGEX           file names matching this regular expression will not be operated on
    accept:                 REGEX           if this is present it overrides the `ignore` and only accepts files matching the regex
*/
$.ajax({
    url: folderURL,
    success: function(data){
        var filesLoaded = 0,
        fileName = '';

        $(data).find("td > a").each(function(){
            fileName = $(this).attr("href");

            if(fileName === '/')
                return;  //to account for the (go up a level) link

            if(/\/\//.test(folderURL + fileName))
                return; //if the url has two consecutive slashes '//'

            if(options.accept){
                if(!options.accept.test(fileName))
                    //if accept is present and the href fails, dont callback
                    return;
            }else if(options.ignore)
                if(options.ignore.test(fileName))
                    //if ignore is present and the href passes, dont callback
                    return;

            if(fileName.length > 1 && fileName.substr(fileName.length-1) === "/")
                if(options.recursive)
                    //only recurse if we are told to
                    exploreFolder(folderURL + fileName, options);
                else
                    return;

            filesLoaded++;
            options.callback(folderURL + fileName);
            //pass the full URL into the callback function
        });
        if(options.then && filesLoaded > 0) options.then(filesLoaded);
    }
});
}

Then you can call it like this:

然后你可以这样称呼它:

var loadingConfig = {
    callback: function(file) { console.log("Loaded file: " + file); },
    then: function(numFiles) { console.log("Finished loading " + numFiles + " files"); },
    recursive: true,
    ignore: /^NOLOAD/,
};
exploreFolder('/someFolderURL/', loadingConfig);

This example will call that callback on every file/folder in the specified folder exceptfor ones that start with NOLOAD. If you want to actually load the file into the page then you can use this other helper function that I developed.

此示例将对指定文件夹中的每个文件/文件夹调用该回调,NOLOAD. 如果您想将文件实际加载到页面中,那么您可以使用我开发的其他辅助函数。

function getFileExtension(fname){
    if(fname)
        return fname.substr((~-fname.lastIndexOf(".") >>> 0) + 2);
    console.warn("No file name provided");
}
var loadFile = (function(filename){
    var img = new Image();

    return function(){
        var fileref,
            filename = arguments[0],
            filetype = getFileExtension(filename).toLowerCase();

        switch (filetype) {
            case '':
                return;
            case 'js':
                fileref=document.createElement('script');
                fileref.setAttribute("type","text/javascript");
                fileref.setAttribute("src", filename);
                break;
            case "css":
                fileref=document.createElement("link");
                fileref.setAttribute("rel", "stylesheet");
                fileref.setAttribute("type", "text/css");
                fileref.setAttribute("href", filename);
                break;
            case "jpg":
            case "jpeg":
            case 'png':
            case 'gif':
                img.src = filename;
                break;
            default:
                console.warn("This file type is not supported: "+filetype);
                return;
        }
        if (typeof fileref !== undefined){
            $("head").append(fileref);
            console.log('Loaded file: ' + filename);
        }
    }
})();

This function accepts a JS | CSS | (common image) file and loads it. It will also execute the JS files. The complete call that needs to be run in your script to load all images and*stylesheets andother scripts could look like this:

这个函数接受一个 JS | CSS | (common image) 文件并加载它。它还将执行 JS 文件。需要在脚本中运行以加载所有图像和*样式表其他脚本的完整调用可能如下所示:

loadingConfig = {
    callback: loadfile,
    then: function(numFiles) { console.log("Finished loading " + numFiles + " files"); },
    recursive: true,
    ignore: /^NOLOAD/,
};
exploreFolder('/someFolderURL/', loadingConfig);

It works amazingly!

它的效果惊人!

回答by Alan

Another option that is pretty short:

另一个很短的选项:

<script type="text/javascript">
$.ajax({
  url: "/js/partials",
  success: function(data){
     $(data).find('a:contains(.js)').each(function(){
        // will loop through 
        var partial= $(this).attr("href");
        $.getScript( "/js/partials/" + partial, function( data, textStatus, jqxhr ) {});
     });
  }
});
</script>