The peculiar behavior of dynamically loading CSS with jQuery

In the development of my app, I am faced with the challenge of dynamically loading CSS and JS. Currently, the solution looks like this:

myapp.loadCss = function(css){
       $("head").append("<link>");
       cssDom = $("head").children(":last");
       cssDom.attr({rel:  "stylesheet",
                 type: "text/css",
                 href: css
                });  
}

myapp.loadJs = funciton(js){
...
//$.ajax call is used in synchronized mode to make sure the js is fully loaded 
}

}

When certain widgets need to be loaded, the typical calls are as follows:

myapp.loadCss('/widgets/widget1/css/example.css');
myapp.loadJs('/wiggets/widget1/js/example.js');

However, occasionally (1 out of 10 or 20 times), the newly created dom elements from example.js fail to retrieve their CSS from example.css. It appears that my loadCss method may not be loading the CSS in a synchronized manner. To address this, I attempted replacing my loadCss function with the following code:

myapp.loadCss(css){
 $('<link href="' + css + '" rel="stylesheet" type="text/css" />').appendTo($('head'));

}

This seemed to resolve the issue (after multiple webpage refreshes for confirmation :-() However, this alternate method did not work in IE7 (and has not been tested in IE6 or IE8).

Are there any better solutions to ensure proper loading of CSS and JS in a synchronized manner?

Answer №1

One method you can use is the following:

const cssElement = $("head").append("<link>");

Implementing this approach can prevent issues that may arise if your script is called twice simultaneously, leading to duplicate tags being added but only one getting updated, resulting in a missing CSS file.

Regarding IE7, a common mistake I encountered is adding a comma after the last element in a dynamically created object:

var exampleObject = {key1: 'value1', key2: 'value2',}

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

What is the best approach for assigning initial values to data retrieved from Vuex?

My objective is to develop an 'edit account' form where users can update their account details. I aim to display the account information in a pre-filled form that includes fields like username, email, and address. Users will be able to make chan ...

IframeResizer.js is automatically readjusting its position to the top left corner (0,0) when a javascript event or

Within our internal web environment, I have implemented IframeResizer.js in a rather basic manner. The child page contains a table generated by a third-party application with mouseover/hidden and javascript tags associated with the TH elements (including a ...

How to obtain the first and last elements of an array using ES6 syntax

let array = [1,2,3,4,5,6,7,8,9,0] This is an example of how documentation might look [first, ...rest] = array will give you 1 and the rest of the array My question now is whether it is possible to only extract the first and last elements 1 & 0 using ...

Troubleshooting issue with findByIdAndUpdate incorrectly updating nested objects with $set method

I'm currently working on developing a feature that will allow my users to have control over the notifications and emails they receive. My approach involves implementing an object with multiple nested objects to achieve this functionality. While ever ...

Implementing jQuery during the navigation between Node routes

Below is a snippet of my jQuery code: $(function () { $('.mnav a').click(function () { el = $('.border'); el.addClass('blink'); el.one('webkitAnimationEnd oanimationend msAnimationEnd animatio ...

Div with Sticky Header and Scrolling Ability

I am working on a project that involves creating a scrollable div with "title" elements inside. I want the title element of each section to stick to the top of the div as I scroll, similar to how a menu sticks to the top of a webpage. An example of this ca ...

How can I avoid triggering the $.get() function multiple times in a row?

I have a main HTML page named myitem.html. I used AJAX to display the itembox, which is loaded from itembox.php file. When I scroll down inside the itembox, new content from the new.php file is appended at the end of the itembox. However, the new content i ...

Adjust picture dimensions when the window changes (using jQuery)

Hey there, I'm in need of some help resizing images on my webpage. I want the images to adjust their size when the page loads or when the browser is resized. The images can be either portrait or landscape, and they will be contained within a div that ...

execute a function after submitting the form

I need to implement a function that will be triggered when submitting a form. This function should work for all forms contained within the div with the id "#js_ajax_form". ( The JavaScript code functions properly in Chrome console // Here is the HTML sni ...

Error Type: Property 'history' is not defined and cannot be read

My goal is to automatically redirect the user to the login page when they hit the /logout route. The authentication process works as expected (jwt token is removed), but I'm encountering issues with the app failing to redirect to /login upon logout. ...

Is it possible to use both the .load function and fadeIn in jQuery simultaneously?

Currently, I am utilizing the .load method to bring in another page using jQuery. Below is the code snippet: $('#page1').click(function(){ $("#content").load("page1.html"); }); While this code works well, I am inte ...

Glitch in the scroll glue directive

Currently, I'm attempting to incorporate scroll-glue in order to automatically scroll to the bottom of a message.html page. My approach involved including the directive 'luegg.directives' in the following manner. (function(){ 'use stri ...

Is there a specific event in Angular.js that triggers when the $scope digest cycle is completed or when the view is refreshed?

Currently, I am making an AJAX request to retrieve data that is needed in the view to generate a list. My goal is to determine when the $scope has been updated and when the view has finished rendering after receiving a successful response. This will allow ...

The success function for an AJAX post request is causing issues

I've been struggling with a simple task. I just want to make an ajax post request to fetch a value from my database and populate it in an input field. Despite going through numerous tutorials, I can't seem to get it right. The server-side MVC con ...

Error message: The compareSync function in Object.bcrypt is indicating that the passed string is undefined. Are there any

Within my rendered Nunjucks template, I have set it up to accept a username and password input from the user. Upon clicking the submit button, the goal is for the system to search through a database in my JavaScript Express file to verify if the entered cr ...

Functions do not retrieve values directly from an array

Here is a code snippet that I have for(var i=0; i < this.arr2.length; i++) { arr.push({ id: i.toString(), label: this.arr2[i], display: () => this.arr2[i] }) } I'm curious why the display is undefin ...

CSS background image with a see-through overlay

I am trying to add a black overlay with an opacity of 0.7 to a full-screen background image. This is the CSS code I currently have: body { background:url(../images/bg.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-backgr ...

Ionic - numerical age selector control

Currently working on a hybrid mobile app and ran into a specific issue. I'm in the process of adding new items to my left side menu, including an age number spinner component (min:18, max:65). After searching through various sources and Ionic documen ...

Using MVC3/Razor to trigger an Ajax request to the Controller

I am working on a Razor view that includes multiple dropdown lists. My goal is to have the ability to clear the values in one dropdown when the value in another dropdown is changed, and then populate it with new values based on the model being used by the ...

Encountering a plethora of errors post-updating Angular application from version 6 to 10

Could you please advise on the optimal method to update my application and provide a solution for peer dependency issues similar to the ones below: Package "ngx-chips" has an incompatible peer dependency with "@angular/animations" (requires "^8.0.0" (ext ...