Load remote CSS file dynamically with jQuery

The below code loads a CSS file dynamically. It’s relatively easy to load all CSS files from the beginning, or just append a link element (ref. Switch stylesheets with jQuery). But it rarely needs to load a file dynamically and wait until those new CSS properties are ready to render new HTML elements.


<script src="/jquery-1.3.2.js"></script>
     // If it's a local file just using $.get() should be fine
    $.getJSON('http://remote-server/css.php?callback=?', function(data){
        //$('head > style:last').html(data); // it doesn't work on IE
        $('body').append('<style>' + data + '</style>');
        // Edit dom tree now. These elements need new CSS properties which should be loaded from the remote file
        $('body').append('<div id="something-special"><h1>Hello World!</h1></div>');


div#something-special h1 {
    color: red;
sleep(10); // it's for test
if (isset($_GET['callback'])) {
    $buf = ob_get_contents();
    echo filter_var($_GET['callback'], FILTER_SANITIZE_STRING), '(', json_encode($buf), ')';
This entry was posted in Tweak and tagged , , . Bookmark the permalink. Both comments and trackbacks are currently closed.