简体   繁体   English

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

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

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? ...获取“js”目录中的所有 JavaScript 文件? How can I do this using jQuery?我怎样才能使用 jQuery 做到这一点?

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.一般来说,这可能不是一个好主意,因为你的 html 文件应该只加载他们实际使用的 JS 文件。 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.只需在将页面提供给客户端之前插入脚本标签。

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.选项 #3 是有一个“加载器”JS 文件,它使用 getScript() 加载所有其他文件。 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.将其放在所有 html 文件的脚本标记中,然后只要上传新脚本,您只需要更新加载程序文件即可。

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);

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.使用 javascript 解析该文件,提取所有 .js 文件。 This will of course be sensitive to the format of the directory listing on your web server / web host.这当然对您的网络服务器/网络主机上目录列表的格式很敏感。

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);
 }

It can be done fully client side, but all javascript file names must be specified.它可以完全在客户端完成,但必须指定所有 javascript 文件名。 For example, as array items:例如,作为数组项:

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);
   } 
 }

@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. @jellyfishtree 如果您创建一个包含目录中所有 js 文件的 php 文件,然后仅通过脚本标记包含此 php 文件,那会更好。 This has a better performance because the browser has to do less requests to the server.这具有更好的性能,因为浏览器对服务器的请求更少。 See this:看到这个:

javascripts.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: :)玩得开心: :)

You could use something like Grunt Include Source .您可以使用Grunt Include Source 之类的东西。 It gives you a nice syntax that preprocesses your HTML, and then includes whatever you want.它为您提供了一个很好的语法来预处理您的 HTML,然后包含您想要的任何内容。 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.这也意味着,如果你正确地设置了你的构建任务,你可以在开发模式下包含所有这些内容,而不是在生产模式下,这非常酷。

If you aren't using Grunt for your project, there's probably similar tools for Gulp, or other task runners.如果您的项目没有使用 Grunt,Gulp 或其他任务运行器可能有类似的工具。

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 发布的脚本。

You can't do that in Javascript from the browser... If I were you, I would use something like browserify .您不能在浏览器中使用 Javascript 执行此操作...如果我是您,我会使用browserify之类的东西。 Write your code using commonjs modules and then compile the javascript file into one.使用 commonjs 模块编写代码,然后将 javascript 文件编译成一个。

In your html load the javascript file that you compiled.在您的 html 中加载您编译的 javascript 文件。

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 except for ones that start with NOLOAD .此示例将在指定文件夹中的每个文件/文件夹上调用该回调,但以NOLOAD开头的文件/文件夹除外 If you want to actually load the file into the page then you can use this other helper function that I developed.如果您想实际将文件加载到页面中,那么您可以使用我开发的其他辅助函数。

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 |这个函数接受一个 JS | CSS | CSS | (common image) file and loads it. (普通图像)文件并加载它。 It will also execute the JS files.它还将执行 JS 文件。 The complete call that needs to be run in your script to load all images and* stylesheets and other scripts could look like this:需要在脚本中运行以加载所有图像和*样式表以及其他脚本的完整调用可能如下所示:

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

It works amazingly!效果惊人!

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将目录中的所有javascript文件包含到angularjs中的html文件中?咕噜咕噜? - Include all javascript files in a directory to a html file in angularjs? with grunt? 如何在目录中的所有文件上运行Illustrator javascript? - How can I run an Illustrator javascript on all files in a directory? 如何动态加载和执行目录中的所有JavaScript文件的? - How can I dynamically load and execute all of the Javascript files in a directory? 我可以使用JavaScript在目录中的所有xml文件中搜索字符串吗? - Can I search all xml files in a directory for a string using javascript? 如何通过javascript(jquery)将html元素的内容设置为php include文件 - how can I set the content of a html element via javascript (jquery) to php include file 如何在JavaScript生成的输出中包含PHP文件的内容? - How can I include the content of PHP files in output generated by JavaScript? 如何在Gjs Gnome Javascript中包含文件 - How can I include files with Gjs Gnome Javascript 在HTML / JavaScript文件中,如何选择要包含的数据文件? - In an HTML/JavaScript file, how can I select a data file to include? 我如何使用javascript将文件的一部分包含在另一个文件中 - how can i include part of a file in another file with javascript 我如何将带有数组的json文件包含到javascript文件中? - How i can include json file with array in to javascript file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM