Search code examples
javascripthtmlcssonloaddelayed-execution

Delay loading of stylesheet in old browser


In a (Wordpress) website's <head>, I have the following code to load an additional stylesheet after all dynamic html and inline CSS created by a (third-party) slider plugin has been created via JS:

<link rel="preload" as="style" type="text/css" href="<?php bloginfo('stylesheet_directory'); ?>/slider-styles1.css" onload="this.rel='stylesheet'">

The reason for the necessity to load that additional stylesheet later than the main stylesheet is that it contains some calc values for height settings which depend on other calculated (inline css) values created by the plugin which again depend on the the size of images loaded by the plugin. A rather complex thing, there was actually some trial and error involved before I got it working, since I don't know what the plugin actually does in which order.


My problem: This works in all current browsers, but in some older browsers (for example Firefox < 55, reported by a user with a very old computer) the related stylesheet is not loaded at all. Apparently (also according to caniuse) older browsers don't know <link rel="preload">.

So my question is if there is anything I can replace that line of code with, which also would work in older browsers?


Solution

  • I found a solution myself: I added an ID to the <link> tag to be able to address it in a simple way and used a simple script wrapped inside a setTimeout function to change the value of the rel attribute.

    Note: Since there is no visible content, there is no visible result in the following snippet window, but the code with the changed attribute can be seen when inspecting the snippet with the browser tools. It also works when the link is inside the <head> section, BTW, which is my real-world situation.

    jQuery(document).ready(function() {
      setTimeout(function() {
         jQuery('#link_to_sliderstyles1').attr("rel", "stylesheet");
      }, 200);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="preload" as="style" type="text/css" href="<?php bloginfo('stylesheet_directory'); ?>/slider-styles1.css" onload="this.rel='stylesheet'" id="link_to_sliderstyles1">