所以我使用 node.js 创建了一个小应用程序,并像这样提供了我的 Assets 文件夹
app.use(express.static('assets'));
现在,在我的 .ejs
文件中,我可以轻松引用图像,例如
var img = document.createElement('img');
img.src = '/img/picture.jpg'
现在,我想要做的是循环遍历该文件夹中的所有图像并将它们显示在页面上。
类似
var images = new Array();
images = { All pictures in the /img directory }
images.forEach(function(image) {
var img = document.createElement('img');
img.src = image;
}
所以我的问题是,如何使用 JS 获取所有静态图像的名称? 我是否必须对目录进行 AJAX 调用才能读取文件名?或者使用 node.js 在服务器端执行此操作,并将图像传递到 .ejs
文件。通常,哪种做法更好(可以是一个单独的问题,但我想我会问)?
提前致谢
最佳答案
So my question is, how do I get the names of all the static images using JS?
客户端在向服务器发出请求之前,根本不知道服务器将响应哪些 URL。
Do I instead have to make an AJAX call to the directory to read the file names?
这将是一种可能的方法。
Or do this server-side with node.js and pass the images through to the .ejs file.
这也行
Typically, which is better practice (can be a separate question but I thought I would ask)?
这取决于。
使用 Ajax 需要第二个 HTTP 请求,但可以缓存响应。
在页面加载时执行此操作会减少请求数量,但是每次加载页面时都必须完成获取列表的工作,并且会增加该页面的大小。
因此,使用唯一可衡量的指标,哪个最好,取决于个人重新加载页面的频率以及列表更改的频率。
关于javascript - 用JS访问ejs文件中的静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48645437/