[removed] capturing load event on LINK

后端 未结 9 1321
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 01:00

i\'m trying to attach an event handler to the load event of a link tag, to execute some code after a stylesheet has loaded.

new_element = document.createElem         


        
9条回答
  •  清酒与你
    2020-11-29 01:44

    Here's what is, in my opinion, a better solution for this issue that uses the IMG tag and its onerror event. This method will do the job without looping, doing contorted style observance, or loading files in iframes, etc. This solution fires correctly when the file is loads, and right away if the file is already cached (which is ironically better than how most DOM load events handle cached assets). Here's a post on my blog that explains the method - Back Alley Coder post - I just got tired of this not having a legit solution, enjoy!

    var loadCSS = function(url, callback){
        var link = document.createElement('link');
            link.type = 'text/css';
            link.rel = 'stylesheet';
            link.href = url;
    
        document.getElementsByTagName('head')[0].appendChild(link);
    
        var img = document.createElement('img');
            img.onerror = function(){
                if(callback) callback(link);
            }
            img.src = url;
    }
    

提交回复
热议问题