link element onload

前端 未结 11 828
予麋鹿
予麋鹿 2020-11-30 03:31

Is there anyway to listen to the onload event for a element?

F.ex:

var link = document.createElement(\'link\');
link.rel =          


        
11条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 04:17

    // this work in IE 10, 11 and Safari/Chrome/Firefox/Edge
    // if you want to use Promise in an non-es6 browser, add an ES6 poly-fill (or rewrite to use a callback)
    
    let fetchStyle = function(url) {
      return new Promise((resolve, reject) => {
        let link = document.createElement('link');
        link.type = 'text/css';
        link.rel = 'stylesheet';
        link.onload = resolve;
        link.href = url;
    
        let headScript = document.querySelector('script');
        headScript.parentNode.insertBefore(link, headScript);
      });
    };
    

提交回复
热议问题