SalimK SalimK - 1 year ago 72
jQuery Question

How to optimize jQuery.getJSON() for geolocalisation

I use jQuery.getJSON() to get location of visitors and based on that location i show/hide a specific div. So because of the server api limit's i want that request to be sent just one time per visitor during his visits, may be using a session or a cache in client side to store that location to be used during his visits ; do you have any suggestion ? or a ready to use implementation ?

$(function () {
$.getJSON('', function (location, textStatus, jqXHR) {
console.log("callback running");
var div = document.getElementById('showadsbayt');
jQuery('#region-name').html(location.country_code );
if (location.country_code != 'MA') { = 'none';

Answer Source

Multiple choices come to mind depending on how complex your implementation needs to be, how many pages your application has and whether you want to hide the location data from the user or not. I'll just list them briefly below.

Save as global variable

This one is really obvious and I'm just putting it here for the sake of completeness, but it's enough if you're making a single page app.

Append the parts of the location data that interest you as query string

This is probably the easiest solution if your app has multiple pages and all you need to do is persist data across them. This also has the effect of exposing location data to the user, allowing them to for example bookmark or share the page with the given location - something that may or may not be desirable in your use case.

Use cookies

Cookies are meant just for that - keeping key-value pairs on the user's machine for later use. You can simply save the location data as a cookie and later check if that cookie is set. If it is, use the data from the cookie instead of making an API call. This also persists between visits, so if you care about the case when your users may change location, you need to set a low expiry or allow them to reset their location.

Also, if you're in the EU, you need to put the stupid cookie law banner on your app somewhere.

Use localStorage

Same thing as with cookies, except a bit more flexible and doesn't work on Opera Mini. Use this if your location data is huge for some weird reason.

Apparently this also falls under the EU cookie law, so prepare your banners if you go down this road.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download