简体   繁体   中英

Where to store data which will be later accessed by Javascript?

I have some set of preset values associated with a item in dropdown list. Since the list is large I don't want to store them in js file with if else block. I found that I can store them in json format but it seems like jquery.getJson() makes http get request for this even if file is stored locally. This may add some delay in fetching values. In my case instant response is really important because these vales will be changed during realtime sound editing feature. I was thinking may be I can load these values on page load itself and store it in some variable and then when required do if else to find particular value. Though I am not really sure if this is right way to do. Please suggest.

Have you thought of DOM storage .

Have a look at this and check it serves any of your purpose.

Well, given your requirements, You'd have to load them by including js files. In main html, you'd have:

<script>
    var GlobalData = {};
</script>
<script src="albums.js"></script>
<script src="songs.js"></script>
...

Then, in albums.js (or any other file) you'd have:

GlobalData.albums = [
   //... your data here
];

Then, to access this data when you need it, just do it straightforward

alert(GlobalData.albums.length);

However, if the amount of data is big, it's better if you don't have it always in memory. You could dynamically load it or save it on localStorage .

Cheers

您提到了jQuery,所以我想$.data可以解决问题-http: //api.jquery.com/data/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM