HTML5 history API to reduce server requests -
i trying develop search filter , making use of html5 history api reduce number of requests sent server. if user checks checkbox apply filter saving data in history state, when user unchecks able load data history rather fetching again server.
when user checks or unchecks filter changing window url match filter set, instance if user tries filter car brands of category change url 'cars?filter-brand[]=1'.
but when mutiple filters applied have no way of figuring out whether load data server or load history.
at moment using following code.
pushstring variable new query string created. var = [],forward = []; if(back[back.length-1] === decodeuri(pushstring)){ //check last val against next url created back.pop(); forward.push(currentlocation); history.back(); return true; }else if(forward[forward.length-1] === decodeuri(pushstring)){ forward.pop(); back.push(currentlocation); history.forward(); return true; }else{ back.push(currentlocation); //add current win location }
you can check if filters equivalent.
comparing objects
this simple function takes 2 files, , lets know if they're equivalent (note: not prototype safe simplicity).
function objequal(a, b) { function tostr(o){ var keys = [], values = []; (k in o) { keys.push(k); values.push(o[k]); } keys.sort(); values.sort(); return json.stringify(keys) + json.stringify(values); } return tostr(a) === tostr(b); }
demo
using url
pass query part of url (window.location.search
) function. it'll give object can compare object using above function.
function parseurl(url){ var obj = {}, parts = url.split("&"); (var i=0, part; part = parts[i]; i++) { var x = part.split("="), k = x[0], v = x[1]; obj[k] = v; } return obj; }
demo
history api objects
you can store objects history api.
window.history.pushstate(someobject, "", "someurl")
you can object using history.state
or in popstate
handler.
keeping track of things
if pull out tostr
function first section, can serialize current filters. can store of states in object, , of data associated.
when you're pushing state, can update global cache
object. code should in handler ajax response.
var key = tostr(parseurl(location.search)); cache[key] = datafromtheserver;
then abstract ajax function check cache first.
function getfilterresults(filters, callback) { var cached = cache[tostr(filters)] if (cached != null) callback(cached); else dosomeajaxstuff().then(callback); }
you can use localstorage more persistent caching, require more advanced code, , expiring data.
Comments
Post a Comment