简体   繁体   中英

A small delay on my page when loading CSS

I am having some "issues" when loading my page, it might take a small second before the css is loaded, so at first I see the "not styled" page, and after a small second it is normal.

My host is 000webhost, but maybe that doesn't matter.

Any tips?

I would recommend you to read this article from Google Developer Resource Prioritization – Getting the Browser to Help You

In short use

<link rel="preload" as="script" href="script-file.js">

For preloading javascript

<link rel="preload" as="style" href="styles-file.css">

For preloading CSS

Another advice would be to try and optimize your website and using resources only when required.

Also nothing to do with your hosting service.

My preferred solution is to move javascript to the bottom of the page and to defer the loading of the CSS as follows:

Wrap the content in a div that has display none and place that basic style inline in the head. Then in your CSS file have .wrap{display:block;} .

Then at the bottom defer the loading of the stylesheet until it has been loaded.

What is happening here is the page content is hidden by default (with the.wrap{display:none} . Then when the CSS file is fully loaded, the .wrap{display:block}` overrides the display none and the page is displayed all at once.

<html>
<head><style>.wrap{display:none;}</style></head>
<body>
        <div class="wrap">
           website content
        </div>





    <noscript id="deferred-styles">
          <link rel="stylesheet" type="text/css" href="style.css" />
        </noscript>
        <script>
          var loadDeferredStyles = function() {
            var addStylesNode = document.getElementById("deferred-styles");
            var replacement = document.createElement("div");
            replacement.innerHTML = addStylesNode.textContent;
            document.body.appendChild(replacement)
            addStylesNode.parentElement.removeChild(addStylesNode);
          };
          var raf = requestAnimationFrame || mozRequestAnimationFrame ||
              webkitRequestAnimationFrame || msRequestAnimationFrame;
          if (raf) raf(function() { window.setTimeout(loadDeferredStyles, 0); });
          else window.addEventListener('load', loadDeferredStyles);
        </script>

</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM