The optimal method for loading CSS and Javascript from an ajax response within a JavaScript function - Ensuring cross-browser compatibility

I am in a situation where I need jQuery to make sense of an ajax response, but due to latency reasons, I cannot load jQuery on page load.

My goal is to be able to dynamically load javascipt and css whenever this ajax call is made. After reading numerous articles on this topic, I haven't found a solution that works consistently across all browsers.

One approach I tried was inserting link/script tags into the javascript response and then evaluating the javascript output after a delay of 300ms. However, this method failed in Chrome, possibly due to a race condition.

Another attempt involved using the following script:

function addJquery() {
      var script = document.createElement("script");
       script.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js");
      script.setAttribute('type', 'text/javascript');
      script.addEventListener('load', function() {
          var script = document.createElement("script");
          document.body.appendChild(script);
      }, false);
  document.body.appendChild(script);
}

While this solution worked in Firefox, it did not produce the desired result in Chrome. I'm unsure of what mistake I may be making here. Can someone please assist me in resolving this issue?

Answer №1

If you happen to include jQuery after the load event has already triggered, you won't encounter any latency issues since the page has already been rendered.

In this scenario, the load event will not be triggered again. One way to handle this is by using a setInterval function to check for the presence of jQuery and then clearing the interval once it's detected.

window.addEventListener('load', function(){

    var script = document.createElement('script');
        script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
    document.getElementsByTagName('head')[0].appendChild(script);

    var inter = setInterval(function(){

        if( jQuery ){
            clearInterval(inter);

            //place your jQuery code here
        }

    },100);

},false);

It's worth noting that setting the type on script elements is no longer necessary as all browsers automatically recognize them as JavaScript.

Answer №2

Fetch the jQuery file through an AJAX request with asynchronous set to false.

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

Is it possible to bulk update a sorted set using the Redis client in Node.js?

Looking to update multiple records in a sorted set using Redis client in Node.js. Currently, I am able to update a single record with client.zAdd(key,{score:score, value:memberId}). Is there a command or function that allows for bulk updates in Redis? I se ...

Typescript does not allow for extending an interface with a data property even if both interfaces have the same data type

I've encountered a peculiar problem with Typescript (using Visual Studio 2012 and TypeScript v0.9.5) that I could use some help clarifying. The code snippet below functions correctly: interface IA { data: any; } interface IB { data: any; } ...

Fill every empty element with elements from another array

I'm struggling to grasp the concept of arrays. I have two arrays and I want to replace the null elements in one with the elements from the other. Here is what I have currently: var arr1 = [1,2,3,4] var arr2 = [null, 99, null, null] arr2.map((item) = ...

Is it necessary for TypeScript classes that are intended for use by other classes to be explicitly exported and imported?

Is it necessary to explicitly export and import all classes intended for use by other classes? After upgrading my project from Angular 8 to Angular 10, I encountered errors that were not present before. These issues may be attributed to poor design or a m ...

Having trouble with Apple Login functionality in Safari on my Angular application

While implementing apple login in my web app, I encountered an issue with Safari browser. Instead of opening the redirect URI in a new tab, it displays a finger touch enabled login popup. This prevents the passing of the redirect URI and causes problems wi ...

Customizing error messages in Joi validationorHow to show custom

Hi there, currently I am utilizing "@hapi/joi": "^15.1.1". Unfortunately, at this moment I am unable to upgrade to the most recent Joi version. This represents my validation schema const schema = { name: Joi.string() .all ...

crafting connections in 3D using TypeORM (ORM)

I attempted to construct a database schema involving users, groups, documents, and permissions. Users can be part of multiple groups Groups can have multiple users Users can possess permissions for documents Groups can have permissions for documents Perm ...

The eel feature results in no output

During my Python program development using the Eel module, I encountered an issue. The problem is that the eel.getImgSrc(path) function returns null when trying to retrieve image's byte data. Take a look at this example: -----web/main.js------ async ...

Ajax-powered Autocomplete Functionality

I am looking to include an autocomplete feature for text in my web application. I have the data stored in a SQL server database table and searched Google to find out how to achieve this using autocomplete. Most examples show using a web service, but I am u ...

When an item in the accordion is clicked, the modal's left side scroll bar automatically scrolls to the top. Is there a solution to prevent this behavior and

When I first load the page and click on the Sales accordion, then proceed to click on Total reported and forecasted sales, the scrollbar jumps back up to the top The marked ng-container is specifically for the UI of Total reported and forecasted sales He ...

Retrieve the v-id-xx attribute value for scoped styling in a Vue Single File Component

When using pure JavaScript to add elements in a Vue Single File Component, the added elements are missing the v-id-xx attribute for scoped CSS. Is there a way to retrieve the component's v-id-hash value using only JavaScript? ...

Working with form data in PHP

There is an AJAX POST request originating from AngularJS, containing a JSON model with various fields and a file: ------WebKitFormBoundarywlEiXuTa9EkwFUWz Content-Disposition: form-data; name="model" {"fname":"and","lname":"and","email":"<a href="/cdn ...

Choose the offspring of an element using jQuery

Currently, I have a function set up to open a modal dialog and populate it with information from the 'dblclicked' node: $(function(){ $(".delete").live('dblclick', function () { var id = $(this).attr('id'); ...

The discrepancy between the heights of a div using Jquery and JavaScript

There is a container div encompassing all the site's content, which dynamically stretches. Additionally, there are multiple other divs that also stretch using the same method as in 20 other sites. Despite trying various methods with jQuery and JavaSc ...

Why won't my JavaScript addEventListener activate on form submission?

I have a basic question as a beginner in JavaScript. I am facing some challenges with my first task involving JavaScript. I decided to learn JS by creating a TODO List, but I am stuck right at the beginning. The event listener that should respond when the ...

"Utilize JavaScript to structure JSON, eliminate redundant entries, and calculate the total number

I'm feeling a bit disoriented, as I have this dataset in json format with timestamps and ids arranged like so: [{ "date":"2016-11-18 19:20:42","id_pa":"7" },{ "date":"2016-11-18 19:04:55","id_pa":"5" },{ "date":"2016-11-19 20:53:42","id_pa":"7" ...

Executing functions with directive controllers

Is there a simple way to call a function on a directive controller by accessing the instance using its id from the parent controller? <my-directive id="id1" /> var dirController = getDirectiveByID("id1"); dirController.someFunc(); If you have any ...

Difficulties encountered when trying to load a URL or API that contains an array in javascript/p5js

I've run into a coding issue that I'm trying to troubleshoot in p5js. My goal is to retrieve data from a URL/API. The line `kursMin[1]...` gives the correct stock value, but the line `kursMin[i]` returns `[object Object]2021-03-124. close` Bo ...

Why do the fontawesome icons fail to appear in my SVG file?

I've encountered a peculiar issue where icons (from fontawesome) are not appearing in my svg. They have always displayed correctly on my personal computer, so for a while I didn't realize that others were having trouble seeing them. For instance ...

Utilize PHP to generate a table from data

I successfully created a table using information retrieved from my database, and everything is displaying as intended. However, I am facing an issue where adding a background color applies it to every row in the table. How can I add a background color wit ...