user2692032
user2692032

Reputation: 781

Loading CSS through jQuery and page load function

Due to some other constrains I have to load my CSS through jQuery like this:

$('head').append($('<link rel="stylesheet" type="text/css" />')
         .attr('href', 'http://path/MyCSS.css'));

The problem is, the usual jQuery page load function

$(function () {
   myFunc();
});

Not working as expected. myFunc is supposed to do something related to loaded CSS. Now as I can not determine when the CSS is downloaded and added to my HTML, I don't know how and when to call myFunc?

Upvotes: 2

Views: 1059

Answers (4)

Andreas Louv
Andreas Louv

Reputation: 47099

There are a lot of problems hooking into the load event on link stylesheet tags but you can use the image.onerror loading hack

var head = document.getElementsByTagName( "head" )[0],
    body = document.body,
    css = document.createElement( "link" ),
    img = document.createElement( "img" ),
    cssUrl = "/path/to/a/css/file.css";

css.href = cssUrl;
css.rel = "stylesheet";
head.appendChild( css );

img.onerror = function() {
    // Code to execute when the stylesheet is loaded
    body.removeChild( img );
}

body.appendChild( img );
img.src = cssUrl;

And then in the img.onerror method:

img.onerror = function() {
    body.removeChild(img);
    jQuery(function($) {
        // stylesheet is loaded and the DOMContentLoaded event is also fired
    });
}

Upvotes: 1

Jose Vega
Jose Vega

Reputation: 27

you try use load instead of ready, sometimes works n_n

the link element has load and error events, so that you can use them to determine if the css is loaded

Upvotes: 0

gramgram
gramgram

Reputation: 565

With an ajax call you can be sure your entire css is loaded.

$( document ).ready(function() {
    $.ajax({
        url: 'your_css_link',
        dataType: 'text',
        success: function(css) {
            $('<style type="text/css">\n' + css + '</style>').appendTo("head");
            myFunc();                 
        }                  
    });
});

Upvotes: 3

robbclarke
robbclarke

Reputation: 749

You should be able to do it by modifying what you have above but doing it in a single call.

$('head').append('<link rel="stylesheet" type="text/css" href="/path/to/stylesheet.css">');

This doesn't work IE less than 8 so you'll need to:

  1. append the before setting its href; or
  2. use IE's document.createStyleSheet() method

Upvotes: 0

Related Questions