Reputation: 1213
I am trying to load a 8MB json file using JSON.parse in Javascript, but the page would freeze for about 1-2 minutes, is there a way to parse async and put a loading info or even percentage info improving the user interface?
I google'd a little bit found jsonstream (https://github.com/dominictarr/JSONStream), my understanding is that it's for nodejs? and could not understand that.
If someone have some simple example shown would be greatly appreciated. Thanks!!
Upvotes: 3
Views: 2957
Reputation: 8065
One thing which might work is to use webworkers: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/basic_usage
This moves the parsing process into a separate thread, which functionally would parse your file asynchronously.
Let's say you have main.js and worker.js. In main.js you could have something like:
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);
}
And then in your worker.js file you could have:
onmessage = function(e) {
var parsedJSON = JSON.parse(e.data)
postMessage(parsedJSON);
}
Upvotes: 3