I haven’t been able to find a good stack overflow thread on this, so I wanted to spur a conversation on it.
What are the various approaches or ways people have for dynamically loading a page for a web application?
To clarify, imagine your web application is like a phone application – you may have various screens – a login screen, a details screen, a settings screen, etc. How would you go about defining them, and then loading them at the appropriate time?
I’d like to define the html for each page in a seperate file, and then load that specific file once the user ‘navigates’ to that page. I dont want to do an actual browser navigation, but just swap contents.
Any thoughts or recommendations?
Are you looking for some sort of javascript lazy loading?
I believe normally a map is built in which you register a specific resource name with its relative path. For example:
This can be taken many steps further by trying to keep a correlation between the key and the actual path value if needed.
In the end, you’d be doing something like (psuedocode):
then on your navigation event (such as button click):
where contentElement is your target domElement you wish to fill with the returned HTML.
This will go fetch the html page if it does not exist, or use the client’s local copy if already fetched before. Additionally, you could use the local storage in the browser assuming you are writing for modern-ish browsers.
As a side note about the resourcemap :
If you namespace the resources properly then you can implicitly know the url needed to get the html. The Dojo toolkit provides good examples of this. Namespacing in a similar fashion can save you some trouble as the directory structure of your app can be used to provide load paths as opposed to manual updates on the object. For example, if you want to load a page at /contextroot/homepage/home.html, then you’d simply invoke a fetch against contextroot.homepage.home.html instead of the following some sort of manually maintained value in the map.