开发者

How to catch onload event on css styles?

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?


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜