Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically load CSS using JS

I am trying to achieve the following:

  • I have a server-side script that generates CSS code depending on GET parameters
  • On user request a JS should now do the following
    • Load a new CSS file
    • When loading is done, fade to the newly loaded style

Problem here is the last step.

It is no problem to add a new CSS file to the DOM, but how do I know when the browser finished loading the file? I cannot start animations using the newly loaded styles until the file is actually loaded.

Alternatively: Is it possible to load a CSS file using Async Requests, and inject the CSS code into the DOM using Javascript without parsing it by hand?

Thank you very much!

Dennis

like image 746
Dennis Kempin Avatar asked Dec 09 '22 10:12

Dennis Kempin


2 Answers

I know this question is quite old, but in case anyone Googles this, here is a function that lets you define a callback to let you know when the stylesheet is loaded:

    var css = function(url, callback) {

         var head = document.getElementsByTagName('head')[0];
         var cssnode = document.createElement('link');

         cssnode.type = 'text/css';
         cssnode.rel = 'stylesheet';
         cssnode.href = url;

         cssnode.onreadystatechange = callback;
         cssnode.onload = callback;

         head.appendChild(cssnode);
     }
like image 87
Dominique Avatar answered Dec 27 '22 22:12

Dominique


there are a nice library for this kind of filters...

maybe you can give that a try:

Yep Nope

Yepnope is an asynchronous conditional resource loader that's super-fast, and allows you to load only the scripts that your users need.

like image 44
balexandre Avatar answered Dec 27 '22 21:12

balexandre