Reputation: 313
I've been going through someone else's code and fixing things up a little bit and I've run into some code I don't quite understand. Could you explain to me what's going on here and the implications of how it's implemented and maybe better solution to handle the session storage for the use case or just a better way to write the code?
//Load Content from Cache if this is not a Refresh or new Page Load
if ((document.referrer!=null)&&(sessionStorage.getItem('lastReferrer')!=document.referrer)){
if (('sessionStorage' in window) && (window['sessionStorage'] !== null)) {
if ('@Name'+window.location.href in sessionStorage){
$("#@Name").html(sessionStorage.getItem('@Name'+window.location.href));
$(window).scrollTop(sessionStorage.getItem('@Name'+'ScrollPos'+window.location.href));
jQuery.data($('#ResponderScripts')[0],'cs_page',sessionStorage.getItem('@Name'+'Page'+window.location.href));
jQuery.data($('#ResponderScripts')[0],'cs_totalPages',sessionStorage.getItem('@Name'+'TotalPage'+window.location.href));
pageLoadedFromCache=1;
console.log('Replaced from Cache: @name url='+window.location.href+' referrer='+document.referrer+' page='+$('#ResponderScripts').data("cs_page"));
}
}
};
// Save Component Content when leaving the page.
$(window).unload(function() {
history.replaceState({}, document.title,window.location.href);
if (('sessionStorage' in window) && (window['sessionStorage'] !== null)) {
var componentContent = $("#@Name").html();
if (componentContent!=null){
sessionStorage.setItem('@Name'+window.location.href, componentContent);
sessionStorage.setItem('@Name'+'ScrollPos'+window.location.href,$(window).scrollTop());
sessionStorage.setItem('@Name'+'Page'+window.location.href,$('#ResponderScripts').data("cs_page"));
sessionStorage.setItem('@Name'+'TotalPage'+window.location.href,$('#ResponderScripts').data("cs_totalPages"));
console.log('stored @name url='+window.location.href+' referrer='+document.referrer+' page='+sessionStorage.getItem('@Name'+'Page'+window.location.href));
}
}
});
Thanks any help is appreciated! If this isn't the place for this let me know and I can remove it.
Upvotes: 0
Views: 1161
Reputation: 1028
This snippet seems pretty clear and thought out to me, but I'll decompose what's going on.
if ((document.referrer != null) && (sessionStorage.getItem('lastReferrer') != document.referrer))
So here we determine if the session is continuous. The statement evaluates true if the referrer and the last known session referrer are different.
if (('sessionStorage' in window) && (window['sessionStorage'] !== null))
Here we determine whether sessionStorage is even a thing in the browser, and whether it's been set. Returns true if it's available and set. I'd move this outside the referral check for safety concerns (Possible null or undefined access).
if ('@Name'+window.location.href in sessionStorage)
Now we determine whether the page itself has a property in the sessionStorage. If it is, then load the content stored in sessionStorage rather than load the page.
The next section is even easier. It registers a callback function to be called when the page is being unloaded (navigation, browser close, etc.) This function performs history.replaceState()
and determines if sessionStorage is available (Again). If it is, it saves a bunch of state info to reload next time the page is accessed.
The only thing I'd do is wrap both the save and load logic in the sessionStorage check. If sessionStorage isn't available, why waste time on the other conditionals at all? Do note that this is in context of the snippet, and may not work out for you in the full app's context.
Upvotes: 3
Reputation: 13177
This code looks to be preserving a page (paginated list?) in local store so that it can be reconstituted from cache. I have rewritten it in a way that I hope adds clarity.
var currentUrl = window.location.href;
// **************************************
// Set some keys that can be used to access the localstore cache
// **************************************
var lastHTMLContent_key = '@Name' + currentUrl;
var lastScrollPosition_key = '@Name' + 'ScrollPos' + currentUrl;
var lastPage_key = '@Name' + 'Page' + currentUrl;
var lastPageTotal_key = '@Name' + 'TotalPage' + currentUrl;
// **************************************
var $ResponderScripts = $('#ResponderScripts');
var $Target = $("#@Name");
// **************************************
// Some tests to determine if we can successfully retrieve an item from the cache
// Note: Moved here for clarity. It is actually important to do these tests in a
// way that prevents null references.
// **************************************
var isSessionStorageAvailable = ('sessionStorage' in window && window['sessionStorage'] !== null);
var isNewReferrer = (document.referrer != null && document.referrer != sessionStorage.getItem('lastReferrer');
var isURLInStore = ( lastHTMLContent_key in sessionStorage );
// **************************************
// **************************************
// Load Content from Cache if this is not a Refresh or new Page Load
// **************************************
if (isSessionStorageAvailable && isNewReferrer && isURLInStore) {
pageLoadedFromCache = 1;
// **************************************
// Fetch prior cached content
// **************************************
var lastHTMLContent = sessionStorage.getItem(lastHTMLContent_key);
var lastScrollPosition = sessionStorage.getItem(lastScrollPosition_key);
var lastPage = sessionStorage.getItem(lastPage_key);
var lastPageTotal = sessionStorage.getItem(lastPageTotal_key);
// **************************************
// **************************************
// Set current content/context based on prior
// **************************************
$Target.html(lastHTMLContent);
$(window).scrollTop(lastScrollPosition);
jQuery.data($ResponderScripts[0], 'cs_page', lastPage);
jQuery.data($ResponderScripts[0], 'cs_totalPages', lastPageTotal);
// **************************************
console.log('Replaced from Cache: @name url=' + currentUrl + ' referrer=' + document.referrer + ' page=' + $('#ResponderScripts').data("cs_page"));
}
// **************************************
// **************************************
// Save Component Content when leaving the page.
// **************************************
$(window).unload(function() {
history.replaceState({}, document.title, currentUrl);
if (isSessionStorageAvailable) {
var targetHTML = $Target.html();
if (targetHTML != null){
// **************************************
// Save existing content for next time...
// **************************************
sessionStorage.setItem(lastHTMLContent_key, targetHTML);
sessionStorage.setItem(lastScrollPosition_key, $(window).scrollTop());
sessionStorage.setItem(lastPage_key, $ResponderScripts.data("cs_page"));
sessionStorage.setItem(lastPageTotal_key, $ResponderScripts.data("cs_totalPages"));
// **************************************
console.log('stored @name url=' + currentUrl + ' referrer=' + document.referrer + ' page=' + $('#ResponderScripts').data("cs_page"));
}
}
});
// **************************************
I think this is how I might approach the more complicated if:
if (
window.sessionStorage && // we can work with sessionStorage
sessionStorage[lastHTMLContent_key] && // a value for this page is in the store
document.referrer && // there is a referrer
document.referrer != sessionStorage.getItem('lastReferrer') // the referrer is not the last referrer
) {
// proper to use cache page data
}
Upvotes: 2