Currently, I am working on a single page app that changes the hash in the URL to load and modify the content of the page. I am contemplating the best approach for managing the JavaScript required by each "page".
I have already developed a History module that tracks the location hash, which could look like domain.com/#/company/about
, and a Page class that utilizes XHR to retrieve the content and display it in the designated area.
function onHashChange(hash) {
var skipCache = false;
if(hash in noCacheList) {
skipCache = true;
}
new Page(hash, skipCache).insert();
}
// Page.js
var _pageCache = {};
function Page(url, skipCache) {
if(!skipCache && (url in _pageCache)) {
return _pageCache[url];
}
this.url = url;
this.load();
}
The cache functionality allows previously loaded pages to bypass the XHR request. Additionally, I am storing the content in a documentFragment, retrieving the current content from the document when inserting the new Page
. This helps minimize the DOM construction process.
Sometimes skipping the cache may be necessary for time-sensitive data.
Here's my dilemma: Most likely, the pages being loaded will require specific JavaScript functions to control various elements like tabs, slideshows, animations, ajax forms, etc.
What is the most effective way to include this JavaScript into the page? Should I add script tags to the documentFragment obtained from XHR? However, if I need to skip the cache and download the fragment again, repeatedly calling the same JavaScript might lead to conflicts, such as redeclaration of variables.
Alternatively, should I append the scripts to the head when fetching the new Page
? This would necessitate the original page knowing all assets needed by every other page.
In addition to determining the optimal inclusion method, how do I address memory management and potential leaks when loading numerous JavaScript components into a single page instance?