1

I believe that I've made a terrible mistake. I have a global JS file that I include via script tag on every single JSP page.

<script type="text/javascript" src="/myGlobalJS.js" ></script>

In that JS file I make a call to get JSON; but I only want that executed once. Right now it executes every time a new JSP page loads.

var myObj = (function(){
    var myData = {};

    return{
        setData:function(data){
            myData = data.response;
     }
   };
})();


(function(){
    $.getJSON(jsonUrl)
        .done(function(data){
            myObj.setData(data.response.data);
        });
 })();

How can I correct this elegantly?

Update: I can see the error of my thinking now. I'm thinking about these JSP pages as an application and when the app loads then it should execute getting this JSON file only one time. There is no persisted UI state across these JSP pages. So I think that I'll have to load the file and call it on every page I need it, unfortunately. Is this true?

fumeng
  • 1,771
  • 5
  • 22
  • 61
  • Executed once per what? – James Mar 07 '16 at 17:59
  • executed once ever. I see the folly in this now .Basically, I only want this executed once while the user is on the site. So if it has been executed on one JSP page then I don't want it executed on any of the others. – fumeng Mar 07 '16 at 18:01
  • 1
    U may add variable in localstorage and some if else statement to verify if data was loaded previously. – loadaverage Mar 07 '16 at 18:07
  • You want it load load only once, but does it matter which page this may load once on? – Bobby W Mar 07 '16 at 18:09
  • It doesn't. But you can access the app from a few different JSP pages...there's no single point of entry. That's why I put it in the global JS in the first place (so every page had access to it). – fumeng Mar 07 '16 at 18:11
  • Well you must be doing something with that response data on the first call, could you not just check if what you are looking for already exists in the app? Because if that data you wanted to fetch doesn't exist, your gonna want to call the JSON fetch again, right? It's hard for my to understand exactly without some more context. – Bobby W Mar 07 '16 at 18:14
  • I do, I populate some data on the page. But if the JSP reloads then that data will have to re-render. Where am I going to check? State doesn't persist, right? I'm not using some global model across JSP pages. – fumeng Mar 07 '16 at 18:25

1 Answers1

0

I've found the answer here:

Global vars across pages

HTML5 supports sessionStorage, which will store variables as long as the session is in use. Only shortcoming is that it doesn't seem to fully support storing objects across all browsers yet. But it's definitely a nifty solution.

Community
  • 1
  • 1
fumeng
  • 1,771
  • 5
  • 22
  • 61