2

I load css

var ss = document.createElement("link");
var url = 'http://site.ru/style.css';
ss.setAttribute("rel", "stylesheet");
ss.setAttribute("type", "text/css");
ss.setAttribute("href", url);
document.getElementsByTagName("head")[0].appendChild(ss);

I want to call function after css loading, but tag link hasn't onload event, is there a way to do it?

2
  • is your javascript running on the same domain ? Commented Jul 28, 2011 at 12:10
  • yes it is. the problem is that i cant do something like ss.onload=myfunc(); Commented Jul 28, 2011 at 12:12

1 Answer 1

4

You currently don't load that css stuff via Ajax, but you could do it. That way, you also have your callback when data transfer has finished. I'm using jQuery in this example to make things short and convinient.

Be aware: This only works if your javascript & your css files are located on the same domain.

$.get('http://site.ru/style.css', function( css ) {
    $('<style>', {
        html: css
    }).appendTo( document.head || document.getElementsByTagName( 'head' )[0] );
});

Simplified vanilla Javascript might look like:

var req;

try {
    req = new XMLHttpRequest();
} catch ( e ) {
    req = new ActiveXObject( 'Microsoft.XMLHTTP' ); // there are plenty more
} finally {
    req.onreadystatechange = function() {
        if( req.readyState === 4 ) {  // simplified/shortened
            var head          = document.head || document.getElementsByTagName('head')[0] || document.documentElement,
                lnk           = document.createElement('style');
                lnk.type      = 'text/css';
                lnk.textContent = lnk.text = req.responseText;

            head.insertBefore(lnk, head.firstChild);
        }
    };

    req.open('GET', 'http://site.ru/style.css', true);
    req.send(null);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Good answer, but I suggest using a framework like jQuery or Prototype here. jQuery offers a simple "ready"-event that can be attached to css files. And the whole AJAX-processing is more straightforward.
@acme: what do you mean ? The DOMContentLoaded event which .ready() internally listens for if available will fire when the DOM is ready. stylesheets and images may not be loaded already at this point, plus I guess the OP wants to insert a stylesheet dynamically beyond pageload.
...and I'm really interested in why someone would anonymously downvote that answer. oh gosh ;)
Any idea how you could do this but keep the relative file locations for loading images etc from the stylesheet?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.