8

I am trying to append a css file using

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

That works great - however, I have some functions that run AFTER the css has been added and I can't figure out a way for these to wait until this file has finished loading ?

How can I do this ?

1
  • Any reason you can't just include the css in the <head> block from the getgo without using jquery? Commented Jan 7, 2012 at 4:00

2 Answers 2

6

Just check when one of the rules of the new CSS has been applied:

$('head').append('<link rel="stylesheet" href="http://cdn.sstatic.net/stackoverflow/all.css?v=d4a5c7ca0d4c" type="text/css" />');

var fakeListener = setInterval(function(){
    if($("body").css("text-align")=== "center"){
        clearInterval(fakeListener)
        // What you want to do after it loads
    }
},50)

(That is a working example)

Sign up to request clarification or add additional context in comments.

2 Comments

I can see how that could work, but it's hacky at best. It also won't work for my scenario, as I don't have the corresponding DOM elements created at the time when CSS is being loaded. The DOM elements are created much later (possibly several minutes later) when user performs some actions on the front end.
Just check for the existence of the element before checking for css rules, something like this: if($('article').length && $('article').css('text-align') === 'center')...
-1

The first thing to do is to put your functions inside the ready method, that will execute those functions after the DOM has loaded.

<script type="text/javascript">
  jQuery(document).ready(function() {
    // Your functions come here
});
</script>

Then just put your script before the </body>. This way the append will be triggered just as the dom loads.

<script type="text/javascript">
$('head').append();
</script>

Another aproach is to use the load event:
Check this link with the working example, within it I've set the body with a green background, it loads the stackoverflow stylesheet that when finishes loading it changes the body to white.
http://jsfiddle.net/CQbqA/1/

1 Comment

You've got it mixed up. The function doesn't need to be wrapped in the DOM ready function, rather it's the second snippet you posted that you place at the end of the body.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.