[英]Include all javascript files in a directory to a html file in angularjs? with grunt?
[英]How can I include all JavaScript files in a directory via JavaScript file?
我有一堆我想包含在頁面中的 JavaScript 文件,但我不想繼續寫
<script type="text/javascript" src="js/file.js"></script>
那么有沒有辦法將所有文件包含在一個目錄中(大小未知)? 我可以做類似...
$.getScript("js/*.js");
...獲取“js”目錄中的所有 JavaScript 文件? 我怎樣才能使用 jQuery 做到這一點?
一般來說,這可能不是一個好主意,因為你的 html 文件應該只加載他們實際使用的 JS 文件。 無論如何,這對於任何服務器端腳本語言來說都是微不足道的。 只需在將頁面提供給客戶端之前插入腳本標簽。
如果你想在不使用服務器端腳本的情況下做到這一點,你可以將你的 JS 文件放到一個允許列出目錄內容的目錄中,然后使用 XMLHttpRequest 讀取目錄的內容,解析出文件名並加載它們.
選項 #3 是有一個“加載器”JS 文件,它使用 getScript() 加載所有其他文件。 將其放在所有 html 文件的腳本標記中,然后只要上傳新腳本,您只需要更新加載程序文件即可。
使用服務器端腳本生成腳本標記行怎么樣? 粗略地說,像這樣 (PHP) -
$handle = opendir("scripts/");
while (($file = readdir($handle))!== false) {
echo '<script type="text/javascript" src="' . $file . '"></script>';
}
closedir($handle);
鑒於您想要一個 100% 的客戶端解決方案,理論上您可以這樣做:
通過 XmlHttpRequest,獲取該目錄的目錄列表頁面(如果目錄中沒有 index.html 文件,大多數 Web 服務器返回文件列表)。
使用 javascript 解析該文件,提取所有 .js 文件。 這當然對您的網絡服務器/網絡主機上目錄列表的格式很敏感。
動態添加腳本標簽,像這樣:
function loadScript (dir, file) {
var scr = document.createElement("script");
scr.src = dir + file;
document.body.appendChild(scr);
}
它可以完全在客戶端完成,但必須指定所有 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);
}
}
@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);
}
?>
索引.php:
<script type="text/javascript" src="javascripts.php"></script>
而已!
玩得開心: :)
您可以使用Grunt Include Source 之類的東西。 它為您提供了一個很好的語法來預處理您的 HTML,然后包含您想要的任何內容。 這也意味着,如果你正確地設置了你的構建任務,你可以在開發模式下包含所有這些內容,而不是在生產模式下,這非常酷。
如果您的項目沒有使用 Grunt,Gulp 或其他任務運行器可能有類似的工具。
你不能在 JavaScript 中這樣做,因為 JS 是在瀏覽器中執行的,而不是在服務器中執行的,所以它對目錄或其他服務器資源一無所知。
最好的選擇是使用服務器端腳本,例如 jellyfishtree 發布的腳本。
您不能在瀏覽器中使用 Javascript 執行此操作...如果我是您,我會使用browserify之類的東西。 使用 commonjs 模塊編寫代碼,然后將 javascript 文件編譯成一個。
在您的 html 中加載您編譯的 javascript 文件。
我一直在尋找這個問題的答案並且遇到了自己的問題。 我在不同的地方找到了幾個解決方案,並將它們組合成我自己喜歡的答案。
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);
}
});
}
然后你可以這樣稱呼它:
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);
此示例將在指定文件夾中的每個文件/文件夾上調用該回調,但以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);
}
}
})();
這個函數接受一個 JS | CSS | (普通圖像)文件並加載它。 它還將執行 JS 文件。 需要在腳本中運行以加載所有圖像和*樣式表以及其他腳本的完整調用可能如下所示:
loadingConfig = {
callback: loadfile,
then: function(numFiles) { console.log("Finished loading " + numFiles + " files"); },
recursive: true,
ignore: /^NOLOAD/,
};
exploreFolder('/someFolderURL/', loadingConfig);
效果驚人!
另一個很短的選項:
<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.