Possible to cache JSON to increase performance / load time?

后端 未结 6 1162
我寻月下人不归
我寻月下人不归 2020-12-13 11:14

I\'m using a JSON file to autopopulate a drop down list. It\'s by no means massive (3000 lines and growing) but the time taken to refresh the page is becoming very noticeab

6条回答
  •  盖世英雄少女心
    2020-12-13 12:03

    I use the browser's cache to ensure that my large chunk of JSON is only downloaded once per session. I program in ASP.NET, but I'm sure PHP has the same mechanisms:

    1. On session start, I generate a random string as session key for my dynamic JavaScripts. This key get stored in the ASP.NET session state under the key JsonSessionID. That way I can refer to it in my page markup.
    2. I have a "generic http handler" (an ashx file) that when called by the browser, returns a .js file containing my JSON.
    3. In my HTML I include the dynamic script:

    The browser will automatically cache any URLs included as scripts. The next time the browser is asked to load a cached script from a URL, it will just load up the file from the local disk. This includes dynamic pages like this.

    By adding the ?v= in there, I ensure that the JSON is updated once per session.

    Edit

    I just realized that your JSON is probably static. If that's the case, you can just put your JSON into a static .js file that you include in your HTML, and the browser will cache it.

    // conversionData.js
    var conversionData = { "a":1,"b":2,"c":3 };
    

    When you include the conversionData.js, the conversionData variable will be in scope with the rest of your page's JavaScript that dynamically updates the drop-downs.

    Edit 2

    If you are serving static files, this blog post has a good pattern for cache-busting based on the file's date modified property. i.e. the file is only downloaded when it is changed on the server.

    I have yet to find a good method for cache-busting JSON created via database lookup tables, other than per-session. Which isn't ideal because the database could change mid-session.

提交回复
热议问题