Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

javascript - Is localStorage fully loaded only after DOM is ready?

I have got a bug with some javascript code that it's hard to reproduce (so no jsfiddle, sorry). Exactly the same browser (FF 37.0.2), but two different machines, and I can only reproduce the bug on one of them.

I suspect the issue has something to do with localStorage and the fact that I check if an item is there outside $(document).ready().

Is that required? Do I need to wait for the DOM to be ready before reliably accessing localStorage? Is my hypothesis plausible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

localStorage is not something that needs to be "loaded" asynchronously. It is available the moment the page starts to load and can be used by Javascript anywhere in the page. If the browser has to fetch values form somewhere (e.g. the disk), that is done synchronously when you request the data or before.

There is no need to wait with $(document).ready() before accessing localStorage. The cause of your issue must be something else.

FYI, you can read the spec on WebStorage here: http://dev.w3.org/html5/webstorage/#dom-localstorage. There is no indication in the localStorage section of that document that JS code must "wait" before accessing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...