There is no straightforward solution to your question because every route will trigger requests when visited. However, you can try resolving the issue by following this trick:
- Declare a global or helper JavaScript file.
- After declaring it, create method(s) inside that must be triggered when visiting a route and save the result in a global variable (e.g., aboutUsDataCache) for access in the route.
- Replace all AJAX request routes actions with methods created for them.
- Add a condition to check if aboutUsDataCache is empty or not. If it's not empty, that means we have already triggered the request, received data, and are in SPA mode, so we do not need to access the method again.
Here is an example from a real project:
module.exports.tmpAppCache = {
fullCadaverList: false,
fullImagesList: false,
fullVideosList: false,
fullPdfList: false,
};
I also have an ajax-helper.js file loaded before routes with methods like this:
export function getFullPdfList() {
// Your AJAX request code here
}
In the routes, I have this code:
{
path: '/pdf/',
async: function (routeTo, routeFrom, resolve, reject) {
if(globalObject.tmpAppCache.fullPdfList !== false){
resolve(
{
component: pdfPage,
},
{
context: {
data: globalObject.tmpAppCache.fullPdfList
}
}
);
}else{ getFullPdfList()
}
},
},
This real project example has been simplified for clarity with some notes included:
- This example uses WebPack so you may see import and export statements.
- Promises have been removed from functions in the code example for clarity.
- To trigger all requests at the start, call all methods in the index route. This ensures that when navigating to any page as in our example, the data is cached and requests are not triggered again.
Best of luck!