Load remote CSS file dynamically with jQuery

These codes are for dynamic loading for remote CSS. It’s easy to load all CSS files from the beginning or just append link element (ref. Switch stylesheets with jQuery). But it rarely needs to load a file dynamically and wait until CSS file has been loaded completely.

test.html:

<html>
<head>
<title>css.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. these elements need new properties of stylesheet
        $('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. Trackbacks are closed, but you can post a comment.

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

  • About

    I'm Nobu, a web developer living in Mountain View, CA. Feel free to comment on any posts. I'm also tweeting on twitter.

  • Archives

  • Recent Posts