简体   繁体   中英

Remove delay when running script on page load

I am currently having trouble with removing delay from my website when I run a function on page load. Is there any way to run a function before page load? Here is the code I am trying to run:

function OnLoad()
if (Cookies.get('Theme') === 'OFF') 
{
$("body").removeClass("dark");
$(".inner-switch").text("OFF");
} else if (Cookies.get('Theme') === 'ON') {
$("body").addClass("dark");
$(".inner-switch").text("ON");
} else {
var Theme;
}
}

And this is how I am running it at page load.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Will's Site</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/navbar.css">
<link href="https://fonts.googleapis.com/css?family=Lato&display=swap" rel="stylesheet"> 
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body onload="OnLoad()">
<!-- Nav Bar -->

<!-- Content -->


<!-- Scripts -->
<script src="js/jquery-3.4.1.js">  </script>
<script src="js/dark-mode.js"></script>
<script src="js/navbar.js"></script>
<script src="js/js.cookie.js"></script>
</body>
</html>

If you need more resources here is the GitHub for the website: My GitHub Link

The best way is to use a server side script like php

<body class="<?php if(?empty( $_COOKIE[ 'theme' ] ) && $_COOKIE[ 'theme' ] == 'ON' ) { echo "dark" } ?>">

So the code is direktly rendering the right theme.

It seems that you are using jQuery so you could execute your code when the DOM is ready to be manipulated using jQuery's ready event which also adds crossbrowser combatibility.

$(document).ready(function() {
 if (Cookies.get('Theme') === 'OFF') 
 {
   $("body").removeClass("dark");
   $(".inner-switch").text("OFF");
 } else if (Cookies.get('Theme') === 'ON') {
   $("body").addClass("dark");
   $(".inner-switch").text("ON");
 } else {
   var Theme;
 }
});

Also remove the onLoad from the body tag and place this code inside an inline or external script after jQuery

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