[英]Why does javascript import take so long?
我正在从我网站自己的前端目录中导入 JSON 文件。 用户单击按钮后,此代码将在浏览器中执行:
const file = await import('./path-to-file')
该文件非常小 - 只有 4KB。 然而,使用console.time()
表明执行此命令大约需要 300 毫秒。 我检查了我自己的 web 速度,速度为 74Mb/s。 我正在使用 Netlify 部署网站,Bitcatcha 说服务器“非常快”,响应时间为 133 毫秒。 我不确定响应时间到底是如何适应这一切的——但总而言之,仅传输 4KB 的数据,300 毫秒似乎太长了。
为什么需要这么长时间,可以做些什么来加快速度?
尝试做:
const file = await require("./path-to-file"); //instead of import();
我相信由于使用了await需要很长时间,所以如果上述方法不起作用,请尝试删除await ,因为await所做的是它停止异步 function 执行直到require(); 已解决。 如果代码在您获取文件内容时继续运行,则总时间应该会缩短。 如果以上都不起作用,试试这个:
const fs = require("fs");
fs.readFile("./path-to-file","utf-8",(err,d)=>{
d = JSON.parse(d);
//Then you do whatever you wanted to do with the file here
});
这是来自浏览器还是服务器端的js?
我从上下文中假设浏览器,它这么慢的原因是因为它喜欢它的状态,等待文件加载。 接受的答案确实使它更快,但问题是 json 文件不能保证在该行代码之后被处理。
异步代码在 js 和其他语言中是一件大事,所以我建议进一步研究,但这里有一些例子:
假设这是 json 文件1
{
count: 2
}
这是js文件
const data = import("path-to-json");
//it immediately goes to the next code
console.log(data.count);
// => undefined or error, since it hasn't finished resolving it
如果您想访问它,则必须使用.then
或await
let data;
import("path-to-json").then(d => {
data = d;
//now you can use data
console.log(data.count)
// => 2
});
//it has still moved on to the next code
//so you still can't use data here
console.log(data.count)
// => undefined or error
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.