Hi there! I am trying to read a text file using JavaScript File Reader API, but my DOM gets unresponsive for a moment while loading the content of the file in the DOM (if the file size is large, (say: 5MB)). I have identified the piece of code which is causing this behavior but I need help how can I fix this?
Below is my HTML Code.
Below is my JavaScript Code for handling file upload
Output
Before Uploading text file.
While Uploading the text file, I clicked on the 'Click Me' button but nothing printed on the console. The DOM was unresponsive for a moment. I don't know why it happened.
After the content got embedded in DOM then the 'clicked' message got printed on the console.
I figured that the below line of code is causing this problem, but I don't know the reason, can anybody please explain me this why this line of code blocking the DOM and how can I fix this?
Top comments (4)
Hi,
this is because in JavaScript you can only process one operation at once (like in PHP).
You could handle this with a dialog that opens while processing so the user doesn't think that the site is "lagging" or something like that.
On the line
const result = await getAsText(file)
The FileReader is processing the file (inside the promise ofgetAsText
, so the line will "pause" execution until thegetAsText
/reader.readAsText
is finished.If you really want to do this "async/ in background/ without freezing" then you would have to use web workers.
Hope this helps.
Btw: I'm not familiar with the FileReader / So i'm not 100% sure about this.
Simon
Hey Simon,
Thanks, I didn't think about Web Workers, yeah with the help of Web Workers this problem will be solved, but I was just wondering can't I achieve async behavior with just using JavaScript Promises or Async/Await in this case?
Hi,
you should read this documentation:
developer.mozilla.org/en-US/docs/L...
and maybe this one: javascript.info/async
The only async behavior of javscript I know / and I use, is:
You can run multiple operations "async" for example if you have 10 http request, you can send them all at "once" and not one after another (with
Promise.all
).All I know is that JavaScript is a single threaded language so you can't archive 100% async behavior with it (correct me if I'm wrong).
So If I'm debugging JavaScript code manually (line for line) I'm go througt it as if it wasn't async, even throug Promises or await/async functions.
Simon
Hey,
Thanks, that helped it😊.