Can JavaScript load a block of text/css instead of a .CSS file?

https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery

To improve Page Loading Time, Google recommends “inlining critical CSS”:


<html>
  <head>
    <style>
      .blue{color:blue;} 
    </style>
    </head>
  <body>
    <div class="blue">
      Hello, world!
    </div>

    <!-- JavaScript to lazy-load CSS file -->
    <script>
      var cb = function() {
        var l = document.createElement('link'); l.rel = 'stylesheet';
        l.href = 'small.css';
        var h = document.getElementsByTagName('head')[0]; h.parentNode.insertBefore(l, h);
      };
      var raf = requestAnimationFrame || mozRequestAnimationFrame ||
          webkitRequestAnimationFrame || msRequestAnimationFrame;
      if (raf) raf(cb);
      else window.addEventListener('load', cb);
    </script>

  </body>
</html>

Instead of the above is it possible to somehow use this alternative:

<div id="CSS-SOURCE" /*style="display:none" */ >
  <?php require 'small.css';?>
</div>    

<!-- JavaScript to lazy-load CSS file -->
  <script>
    var cb = function() {
    var l = document.createElement('link'); l.rel = 'stylesheet';
    l.href = 'small.css';
    var h = document.getElementsByTagName('head')[0]; h.parentNode.insertBefore(l, h);
  };
  var raf = requestAnimationFrame || mozRequestAnimationFrame ||
          webkitRequestAnimationFrame || msRequestAnimationFrame;
  if (raf) raf(cb);
     // else window.addEventListener('load', cb);
  else window.addEventListener('load-from-div-CSS-SOURCE', cb);
</script>

I have a crunched CSS file which is very small and I would prefer to load the CSS file on the server into the above <div id="CSS-SOURCE" /*style="display:none"*/>

If this technique was possible it would eliminate a wasted and time consuming Http Request.

1 Like

Why are you slowing the running of the JavaScript by making it wait for the load event? As the DOM has already loaded at that point the script can run immediately without needing to wait for all the images to load.

1 Like

@felgall

How do I stop it waiting for the page to load?

I was hoping to include(…) the CSS file on the server and then to use JavaScript to load the CSS contents inside the script tags to prevent a Http request.

Is it possible?

I looked at the JavaScript and could not understand how to call and transfer the CSS file before the DOM loaded.

I don’t see why an animation frame is being used so meanwhile to prevent the annoying flicker on every page load I reverted back to using the following PHP:

<head>
...
...
<?php 
$css = file_get_contents('http://subs.because-loads-a-little-quicker.com/assets/css/style-jj-2016-02-04.css');

echo $style = <<< ___TMP
   <style type="text/css">
      $css
   </style>
___TMP;
?>
...
...
</head>

This seems very effective especially since the crunched CSS file is less than 4K and eliminates the need to load the additional JavaScript required to activate the “Lazy-Loading Technique”.

I appreciate the CSS file is loaded for every page but according to Google Analytics the Average Page Views is 2.39 and Session Duration 00:01:28 minutes, so they can afford to wait for the time it takes to load the additional 3.9kB file.

Mission accomplished but will be unable to sleep tonight not knowing if loading the CSS file before the page load had completed would have been a better option :frowning:

To load the CSS before the page loads simply requires that the JS be in the head of the page but after the tag in the DOM that you are referencing to add the CSS.

1 Like

If the JavaScript is in the header then CSS lazy-loading will not be possible.

I may as well just use the normal link method:

<link rel="stylesheet" href="style.css" media="screen">

https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery

One thing to remember is that files requested by JavaScript do not count toward the 8 (or 2 in older browser) limit on the number of files that can load at the same time.

Many thanks.

I will give it a try and let you know if there is an improvement.

I tried using JavaScript in the header and PingDom to test the results. Unfortunately the difference was negligible and sometimes even took longer. The difference I think was due to the shared internet traffic.

The screen also had an annoying flicker due to the complicated, position:fixed navigation menu. To eliminate the flicker would have meant transferring quite a bit of the CSS script and hard-coding the script into style header tags.

The crunched CSS file size is about 3.9kB so I reverted back to inserting the PHP file_get_contents(‘style.css’) between the style tags.

Maybe using JavaScript in the header with larger CSS files would make a difference and worth trying.

Well at least now you are not left wondering if there was a better alternative that you’d overlooked.

1 Like

Yes many thanks, I should have no problems sleeping tonight :slight_smile:

Google recommended the changes which I suppose may make a difference with large CSS files. In future I will take their advice with a pinch of salt!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.