link element onload

前端 未结 11 868
予麋鹿
予麋鹿 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:19

    Another way to do this is to check how many style sheets are loaded. For instance:

    With "css_filename" the url or filename of the css file, and "callback" a callback function when the css is loaded:

    var style_sheets_count=document.styleSheets.length;
    var css = document.createElement('link');
    css.setAttribute('rel', 'stylesheet');
    css.setAttribute('type', 'text/css');
    css.setAttribute('href', css_filename);
    document.getElementsByTagName('head').item(0).appendChild(css);
    include_javascript_wait_for_css(style_sheets_count, callback, new Date().getTime());
    
    function include_javascript_wait_for_css(style_sheets_count, callback, starttime)
    /* Wait some time for a style sheet to load.  If the time expires or we succeed
     *  in loading it, call a callback function.
     * Enter: style_sheet_count: the original number of style sheets in the
     *                           document.  If this changes, we think we finished
     *                           loading the style sheet.
     *        callback: a function to call when we finish loading.
     *        starttime: epoch when we started.  Used for a timeout. 12/7/11-DWM */
    {  
       var timeout = 10000; // 10 seconds
       if (document.styleSheets.length!=style_sheets_count || (new Date().getTime())-starttime>timeout)
          callback();
       else
          window.setTimeout(function(){include_javascript_wait_for_css(style_sheets_count, callback, starttime)}, 50);
    }
    

提交回复
热议问题