简体   繁体   中英

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 ?

    <script>
    $(function () {
        $.getJSON('http://freegeoip.net/json/?callback=?', function (location, textStatus, jqXHR) {
            console.log("callback running");
            console.log(textStatus);
            console.log(jqXHR);
            var div = document.getElementById('showadsbayt');
            jQuery('#region-name').html(location.country_code );
              if (location.country_code != 'MA') {
                      div.style.display = 'none';
              }
        });
    });
</script>  

using Web Storage , code below will find if the user visit your page or not if not visited ajax will make a request and an expire date will be set and you can change value in days or set 0 to be for ever and sure if visited ajax won't request.

  < script > $(function() { var expire = 30; //in days ====> 0 == for ever if (!localStorage["visited"] || (+localStorage["visited"] <= new Date().getTime() && +localStorage["visited"] > 0)) { localStorage["visited"] = (+expire * 24 * 60 * 60 * 1000) + new Date().getTime(); localStorage["visited"] = expire == 0 ? 0 : localStorage["visited"]; $.getJSON('http://freegeoip.net/json/?callback=?', function(location, textStatus, jqXHR) { console.log("callback running"); console.log(textStatus); console.log(jqXHR); var div = document.getElementById('showadsbayt'); jQuery('#region-name').html(location.country_code); if (location.country_code != 'MA') { div.style.display = 'none'; } }); } }); < /script> 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM