Saturday, December 10, 2011

how to dynamically import CSS with jQuery

1 comment:

  1. Note that the JavaScript code does not wait for the Style Sheet to be imported to continue run time. For example, for the style sheet main.css containing:
    p { color: red }

    Your code:


    $('p').css('color','green')
    $('<link/>').attr('href','main.cs').insertAfter('head link:last')
    console.log($('p').css('color'))

    This will return green because the HTTP fetch of the file main.css is done in the background. One work-around will be:

    setTimeout("console.log($('p').css('color'))",1000), allowing 1 second for the HTTP transaction to be over, but even that is really bad because:

    - HTTP transaction time changes all the time and can take more than 1 second


    Yet, you can have some type of recursive function that check for style sheet every 5 milliseconds.

    ReplyDelete

Note: Only a member of this blog may post a comment.