Is it possible to use jQuery to add a CSS style and execute a function simultaneously

I need help with adding a CSS file to the current HTML page using jQuery. Here is what I have:

    var css = jQuery("<link>");
    css.attr({
      rel:  "stylesheet",
      type: "text/css",
      href: "http://domain.com/chron/css/jquery.gritter.css"
    });
    $("head").append(css);

After the CSS file is downloaded, I want to call a specific function. My concern is ensuring that the CSS file is fully downloaded before calling the function. Can someone guide me on how to achieve this?

Answer №1

Have you considered using AJAX to fetch the data and then injecting it into a STYLE element?

$.ajax( {
    url: 'http://website.com/style/jquery.notify.css'
    dataType: 'text'
    success: function( info )
    {
        $( '<style>' )
            .attr( 'type', 'text/css' )
            .text( info )
            .appendTo( 'head' );

        yourCustomFunction();
    }
} );

Answer №2

It is important for the <link> tag to have an attribute called complete, which should be set to true once it has finished loading. One way to check this is by testing it every 50 milliseconds or using the onload event.

For example:

var css = jQuery("<link>");
css.attr({
  rel:  "stylesheet",
  type: "text/css",
  href: "http://domain.com/chron/css/jquery.gritter.css"
})
.load(function() { /* callback */ });
$("head").append(css);

//Since it's unsure whether the onload event works on link elements,
//try this approach instead:
setTimeout(function(){
    if(!css.complete)
    { setTimeout(arguments.callee, 50); }
    else
    { /* callback */ }
}, 50);

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

Symphony 5 and Encore: Issue with Bootstrap JS Loading

Encountering issues while trying to integrate Bootstrap's js with Symfony 5, encore, stimulus, etc... All required dependencies like jquery, popper, corejs are installed and functioning, except for Bootstrap's JS components. The compilation of ...

The custom JavaScript image viewer is experiencing a decreasing loading speed with each press of the "next" key

I have developed a customized image viewer that functions properly, however, the speed decreases each time I navigate to the next or previous image using the arrow keys. As I progress to the 10th image, it may take several minutes to load or even freeze co ...

What is your approach to setting up this navigation system with HTML and CSS?

Navigation Nav w/ Hover State Can you create a navigation menu using HTML and CSS? The white box serves as a placeholder for a logo. Note: The "Products" link has a drop-down menu feature. See my current implementation below, although it's not ye ...

What is the method to integrate HTML tags as native elements within my iOS app?

I am working on creating a custom control that will allow me to convert HTML tags into native tags. For example, when I input the following: label.text = @"&lt;b&gt;&lt;i&gt;Hello World&lt;/i&gt;&lt;/b&gt; The output shoul ...

Issue with Axios in my React Application: Unidentified SyntaxError

As I attempt to connect to my database using axios, a frustrating error appears in my vsCode terminal. The error message reads as follows: SyntaxError: C:\Users\Kelly Owoju\Desktop\Kelly Bright\my-web-app\node_modules\a ...

Dealing with jQuery woes: struggling to precisely position an element

I've been attempting to use jQuery to position a #logo div at the center of a centered #content div, but I'm experiencing inconsistent results. Sometimes it works perfectly, while other times it does not. Particularly in Safari on the iPad, it of ...

The fixed background-attachment feature does not function properly in Chrome when it is contained within a scrolling div

Essentially, if a background image is placed within a scrolling div, it will no longer remain fixed and will revert back to scrolling: CSS: <div class="wrapper"> <span></span> </div> HTML: html, body{ width: 100%; height: ...

Once the Ionic platform is prepared, retrieve from the Angular factory

I have created a firebase Auth factory that looks like this: app.factory("Auth", ["$firebaseAuth", "FIREBASE_URL","$ionicPlatform", function($firebaseAuth, FIREBASE_URL, $ionicPlatform) { var auth = {}; $ionicPlatform.ready(function(){ ...

Tips for accessing external JSON data and implementing it in a JavaScript navbar

Starting with this as a reference point, I am looking to modify it to read data from an external data.json file. My familiarity with JQuery is limited, but I have been able to achieve the desired outcome by using var JSON = {...same structure as from da ...

Module for Npm that includes unique code for both proxy support and non-proxy support configurations

Is there a way to develop a javascript library (available as a module on npm) with multiple implementations based on the level of proxy support in the environment where it is executed (transpiled to)? From my understanding, babel may not easily transpile ...

Switching between filters using AngularJS toggle buttons

Currently, we are in the process of converting a jQuery application into an Angular application using JavaScript. The existing jQuery app functions, but we aim to transform it into a full-fledged app utilizing the Angular framework. The main concept behin ...

The Chrome browser is failing to detect the hover function of the Surface Pen stylus

Encountering an issue with the hover pseudo-class not functioning properly on Surface pad's Chrome browser. The hover effect is working as expected in other browsers, but not in Chrome. I am using a Surface pen to test the hover functionality. HTML: ...

Error with the `this` keyword in TypeScript - value is undefined

I'm encountering an issue with my AWS Lambda function written in TypeScript that calls functions from different classes. The problem is that I am receiving 'undefined' for the existingProducts variable, even though it functions correctly whe ...

Modifying the function name or element ID in a HTML template can cause it to cease functioning

I'm currently working on developing an app using Django and I've encountered a strange issue. In my template, I have the following code: <div class="form-group"> <input name="Data_inserimento_entry" type="date" class="form-control" i ...

Applying CSS text-shadow to an input field can cause the shadow to be truncated

I've encountered an issue when applying text-shadow to an input field, where the shadow appears to clip around the text. Here is the CSS code I used: @import url('https://fonts.googleapis.com/css2?family=Jost:ital,wght@0,100..900;1,100..900& ...

Express not collaborating with Socket IO namespace

Recently, I attempted to establish a namespace on the backend of my project. Here is a snippet of the code: const server = require("http").createServer(app); const connectedUsers = {}; const io = require("socket.io")(server, { path: "/socket", serveC ...

Issue with parsing Mongoose response accurately

I'm fairly new to working with mongoose and have been struggling to find a solution to my current issue. My goal is to query my MongoDB database (hosted on mlab) and pass an object literal to the front end template. I am using hoganjs for templating ...

JavaScript - Verify if all properties belonging to an object are set to true

I'm facing a challenge with an object that contains various fields which could potentially be set to true for a user, similar to a list of achievements. If I have an object like {one: true, two: false, three: true}, how can I prevent the function from ...

Tips on retrieving Bootstrap selectpicker value by using loops in Jquery

I am attempting to perform a basic validation using jQuery, where I need to iterate through all elements to check for the existence of values. The validation script is working well except for the jQuery selectpicker functionality. Here's what I have t ...

SoundCloud authentication failed because the sign-in callback is attempting to access a frame from a different origin

Latest SoundCloud SDK Version About a year ago, I successfully registered my App. To my surprise, today I found that the SoundCloud (SC) sign-in feature is no longer working. Upon clicking the button, a SC pop-up window appears with the message "Allow ...