[英]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.