gpt4 book ai didi

javascript - 解析大型 JSON 文件时页面卡住

转载 作者:行者123 更新时间:2023-11-29 10:41:16 25 4
gpt4 key购买 nike

我正在尝试在 Javascript 中使用 JSON.parse 加载一个 8MB 的 json 文件,但是页面会卡住大约 1-2 分钟,有没有办法解析异步并放置加载信息甚至百分比信息来改善用户界面?

我用 google 搜索了一下 jsonstream ( https://github.com/dominictarr/JSONStream ),我的理解是它是针对 nodejs 的?并且无法理解。

如果有人展示了一些简单的例子,我们将不胜感激。谢谢!!

最佳答案

可能有用的一件事是使用网络 worker :https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/basic_usage

这会将解析过程转移到一个单独的线程中,该线程在功能上会异步解析您的文件。

假设您有 main.js 和 worker.js。在 main.js 中你可以有类似的东西:

var myWorker = new Worker("worker.js");
myWorker.postMessage(jsonValue); //jsonValue = your json file

myWorker.onmessage = function(e) {
var parsedJSON = e.data;
console.log('Message received from worker', parsedJSON);
}

然后在您的 worker.js 文件中,您可以:

onmessage = function(e) {
var parsedJSON = JSON.parse(e.data)
postMessage(parsedJSON);
}

关于javascript - 解析大型 JSON 文件时页面卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28642193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com