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.

test.html:

<html>
<head>
<title>test.html</title>
<script src="/jquery-1.3.2.js"></script>
<script>
$(document).ready(function()
{
     // If it's a local file just using $.get() should be fine
    $.getJSON('http://remote-server/css.php?callback=?', function(data){
        //$('head').append('<style>');
        //$('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>');
    });
});
</script>
</head>
<body>
</body>
</html>

css.php:

<?php
ob_start();
?>
 
div#something-special h1 {
    color: red;
}
 
<?php
sleep(10); // it's for test
if (isset($_GET['callback'])) {
    $buf = ob_get_contents();
    ob_clean();
    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.