简体   繁体   中英

Load a custom style before the whole page is loaded

I need to load different CSS files in contains different colors like a style switcher. and I want to load the color.css before DOM is loaded. I tried the window.onload but always I see default.css is loaded before.

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="keywords" content=""> <meta name="description" content=""> <meta name="author" content=""> <title>Style switcher</title> <!-- ===== Bootstrap CSS ===== --> <script> window.onload = function() { $('#theme').attr({ href: 'css/colors/red.css' }); } // document.addEventListener("DOMContentLoaded", () => { // $('#theme').attr({ // href: 'css/colors/red.css' // }); // }); </script> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- ===== Custom CSS ===== --> <link href="css/style.css" rel="stylesheet"> <!-- ===== Color CSS ===== --> <link href="css/colors/default.css" id="theme" rel="stylesheet"> <script src="js/jquery.min.js"></script> </head> <body> <!-- ===== Main-Wrapper ===== --> <div id="wrapper"> <!-- ===== Top-Navigation ===== --> <nav class="navbar navbar-default navbar-static-top mb-0"> <div class="navbar-header"> <div class="top-left-part"> <a class="logo" href="index.html"> <b> Test </b> </a> </div> </div> </nav> </div> </body>

First of all you are trying to use jQuery before it is available, so that won't work.

Instead of changing the src of the link, you could just create a link tag dynamically with the correct source. I make use of an IIFE to make the function execute directly ones it's loaded

Here is a small snippet that creates a link tag with the correct CSS source, you can change the source the whatever you need.

<script>
  (function () {
    const style = document.createElement("link"); // Create link element
    style.rel = "stylesheet"; // Set relationship to be a stylesheet
    style.href = "css/colors/red.css"; // Set the path to the CSS file

    document.head.appendChild(style); // Add link tag to the head element
  })();
</script>

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