How to apply inline and/or external CSS loaded dynamically with jQuery

Given a path to your stylesheet (or some URL that will generate valid CSS):

var myStylesLocation = "myStyles.css";

…either one of these should work:

Load using AJAX

$.get(myStylesLocation, function(css)
{
   $('<style type="text/css"></style>')
      .html(css)
      .appendTo("head");
});   

Load using dynamically-created <link>

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

Load using dynamically-created <style>

$('<style type="text/css"></style>')
    .html('@import url("' + myStylesLocation + '")')
    .appendTo("head");

or

$('<style type="text/css">@import url("' + myStylesLocation + '")</style>')
    .appendTo("head");

Leave a Comment