Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Lazy Loading in Chrome

I've ran into some weird cases of positioning problems when lazy loading CSS in Chrome, e.g. the positioning of some elements (absolute, relative and cascaded) is off by sometimes huge margin.

Basically what I'm doing is leaving out the standard loading of the stylesheet via an link-Tag and instead placing a placeholder span-Tag for the sake of having an easy way to retrieve the URL later on at the end of the body-Tag. After the DOM loaded fully, I replace the span-Tag with a generated link-Tag like this:

loadCSS: function()
{
    var el = jQuery('.is_css');
    if(!el.length) return;

    // Build link element
    var linkEl = jQuery('<link />').attr({
        media: 'all',
        type: 'text/css',
        rel: 'stylesheet',
        href: el.data('src')
    });

    el.replaceWith(linkEl);
}

I can verify that the CSS is fully loaded as most of the elements are looking exactly as if I embed the CSS directly in the head-Tag. My guess is that Chrome doesn't correctly calculate positions in some circumstances for absolute or relative positioned elements when the CSS is loaded after the DOM has been loaded.

I would like to provide you with HTML / CSS Snippets, unfortunately it's out of scope to isolate the falsely rendered Elements. So instead I'm asking if anybody encountered similar problems that can cause this behaviour. Maybe there are some general hints on how to fix such problems.

Kind regards

like image 810
stlvc Avatar asked Jun 16 '15 14:06

stlvc


1 Answers

Sutuma,

The methodology you are trying could have strong performance impact. As a principle CSS need to be loaded before html DOM is rendered to have an effect. My guess is your html is rendered before CSS get loaded. Here are the option you may try: 1. Load all css in html header tag 2. Reload your html page one css is content is downloaded. 3. You can use html templating with (require js + require css plugin) for lazy loading.

require js , require-css plugin

like image 176
sach Avatar answered Sep 22 '22 06:09

sach