On my website I am displaying a country specific icon for the visitor. I'm doing this by setting a data-country variable in the head of the html document and loading a javascript file that sets the local storage value once when the homepage is visited.
I only want to run the geo.js script once as it can be a performance hit, so I included the conditional, if the first segment is empty then load the geo.js file. But if the users first visit to the site is anywhere other than the homepage the geo.js file is not loaded and the country code is not selected.
Here is my current code:
<head {if segment_1 == ''}data-country="<?php $country_code = $_SERVER["HTTP_CF_IPCOUNTRY"]; echo $country_code; ?>">
{if segment_1 == ''}
<script src="{cdn_url}{exp:setversion path='/js/geo.js'}"></script>
{/if}
Here are the contents of the geo.js file:
var countrySet = localStorage.getItem('country');
if(countrySet !== null && countrySet == 'UK') {
window.location='http://website.com/uk';
}
// If country is not stored, get it from the <head> element
if(countrySet === null) {
var country = document.getElementsByTagName("head")[0].getAttribute("data-country");
// Store country
localStorage.setItem('country', country);
if(country == 'UK') window.location='http://website.com/uk';
}
Question
Is there a way to load the geo.js script only once per site wide visit? Right now if I take away the conditional the script runs on each page load.
geo.js
more performant so its not as noticeable. I will update this question with the proper phrasing. Do you think thegeo.js
script is small enough to run before every page load and be unnoticeable?