Redirecting based on GeoIP location after the DOM has completely loaded

Below is a JavaScript snippet that redirects based on GEOIP :

<script type="text/javascript">

        // Function to call FreeGeoIP after page load
        function newyorkGeoIP() {
            var script = document.createElement('script');
            script.src = "//freegeoip.net/json/?callback=nyGeoIP";
            document.getElementsByTagName('head')[0].appendChild(script);
        }

        // Callback function for the GeoIP response
        function nyGeoIP(d) {
            if (d.country_code === 'XX') {
                window.location = 'http://www.domain.com';
            }
        }
        
        // Call the newyorkGeoIP function after DOM ready
        document.addEventListener("DOMContentLoaded", function(event) {
            newyorkGeoIP();
        });
        
</script>

Could someone advise on how to modify this code to ensure that the FREEGEOIP server is called after the DOM has loaded?

Due to occasional unresponsiveness of the FreeGeoIP server, page rendering is delayed, sometimes causing loading times of 1-2 minutes as reflected in tools like GTmetrix and WebPageTest.

Answer №1

To incorporate the jquery library, follow these steps:

<script type="text/javascript">
$(document).ready(function(){
var script = document.createElement('script');
        script.src = "//freegeoip.net/json/?callback=myGeoIP";
        document.getElementsByTagName('head')[0].appendChild(script);
        function myGeoIP(data) {
            if (data.country_code === 'XX') {
                window.location = 'http://www.example.com';
            }
        }
})

</script>

Answer №2

What is the best JQuery library to include? I am currently only using:

1.7.2 1.8.18

The code you shared previously is not functioning properly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The smooth shading in Three.js is giving off a flat appearance

When loading .stl files, I'm using MeshStandardMaterial without adjusting the flatShading property since it is set to false by default. https://i.sstatic.net/zbCiR.png The outcome appears rather dull to me. Even when attempting to toggle flatShading ...

The functionality of d3.dispatch() is not performing as anticipated

Recently, I delved into the world of D3.js to explore its capabilities. One particular concept that caught my attention is d3.dispatch(), and I've been experimenting with it for about a week now. Below is a simple example: <script src="d3.min. ...

Loading your NextJS page with a full-page loader

I am looking to create a full-page loader for my NextJS app, similar to this example: https://jsfiddle.net/yaz9x42g/8/. The idea is that once the content is loaded, it should be revealed in a visually appealing way. I want to build a reusable component tha ...

using node and express to route and pass variables to a required module

In my primary index.js file, I have the following code: var express = require('express') require("dotenv").config(); const db = require('./services/db_service').db_connection() const customers = require('./routes/custo ...

What is the process for NPM to execute a command that is not located in the path directory?

When I try to run the ava command from my project directory that contains AVA tests, I encounter an issue because it is not in my path. In my project, the npm test command is configured as ava tests/*.js --verbose, and mysteriously manages to execute the ...

Error: Trying to access 'whenReady' property of undefined variable is not allowed

As a beginner in electron app development, I am facing an issue when running npm start from the terminal. The error message I receive is: TypeError: Cannot read properties of undefined (reading 'whenReady')... This specific problem seems to be ...

Error encountered on Windows 10 version 10.0.19044 during library installation with npm

I've encountered an error while trying to run or install libraries for a project within our organization. E:\GIT\bookshelf>npm install npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail= ...

Guide on transferring a 200MB database to an HTML5 web page executed locally

In the process of creating a search tool for internal use within my organization, I have established a deployment strategy that involves: Storing an HTML5 web page on the file server. Keeping a 200MB JSON or JavaScript file in another location. Currentl ...

Comparing the efficiency of using arrays versus mapping to an object and accessing data in JavaScript

When considering the basics of computer science, it is understood that searching an unsorted list typically occurs in O(n) time, while direct access to an element in an array happens in O(1) time for HashMaps. So, which approach yields better performance: ...

Guide on embedding PHP code into a HTML div element using JQuery

I am having trouble loading PHP code into a div tag to display the results. The code I have listed below does not seem to work for me. If anyone can offer assistance in resolving this issue, I would greatly appreciate it. Here is the code snippet: <h ...

What is the process for sharing your website content on Google Blogger?

I am currently developing a dashboard for a small business website and I would like to implement a feature that allows users to post directly to their Blogger blog from the dashboard of their own website. This eliminates the hassle of having to switch betw ...

Encountering issues with adding an item to the to-do list in React, with the error message "Each child in the list must have a unique key prop"

Having trouble creating a to-do list and encountering an error when using the addItemToList function. The specific error message reads: Each child in a list should have a unique “key” prop Application code snippet: function App() { const [currentIte ...

Transforming Form Input Fields into a Nested JSON Format with the Power of JQuery

I'm facing a challenge in converting the input fields below into a nested JSON file structure in my HTML page. Despite trying various methods, I haven't been successful yet. These inputs are retrieved through AngularJS ng-repeat. Any assistance o ...

What is the best way to create three distinct fractions in JavaScript that cannot be simplified?

I have a specific requirement to create 3 fractions with the following conditions: The denominator remains constant The numerator must be unique and fall within the range of 1 to three times the denominator The fraction should not be reducible (e.g., 2/6 ...

"Track the upload progress of your file with a visual progress

I have written this code for uploading files using Ajax and PHP, and I am looking to incorporate a progress bar to indicate the percentage of the upload. Here is the code snippet: <script> $("form#data").submit(function(){ var formData = new ...

Clear Input Field upon Selection in JQuery Autocomplete

I've been experimenting with the Azure Maps API to add autosuggestions for addresses in an input field. https://github.com/Azure-Samples/AzureMapsCodeSamples/blob/master/AzureMapsCodeSamples/REST%20Services/Fill%20Address%20Form%20with%20Autosuggest. ...

Does binary search maintain its usual efficiency?

Does binary searching remain efficient and effective if an array inherits from an object? ...

Efficient Local Database with Javascript

When storing a substantial amount of data, such as a big hashmap in JavaScript, what would be the optimal format for quick retrieval while also supporting Unicode? Would XML or JSON be better suited for this purpose? ...

Running the test suite in another tab is causing it to fail

I am experiencing an unusual issue in my protractor UI test. During one of the tests, I need to click on a link that opens in a new tab. The test passes when run individually, but fails when run as part of the test suite. I would appreciate it if you coul ...

Modify the text of a button depending on the condition and user interaction within an ng-repeat loop in AngularJS

I have a scenario where I am displaying a list of users with two buttons for Start and End using the ng-repeat code: <div class="list-group" ng-repeat="patient in patients" > <a href="#" class="list-group-item" ng-click="chat ...