skip to Main Content

I’m trying to add preloader on my theme. When I’m using this code in functions.php then It work fine. But I’m not interest use CSS & JS on functions.php

Please help me.

add_action('init', 'Devnuru_Preloader');
function Devnuru_Preloader()
{
  if (! is_admin() &&  $GLOBALS["pagenow"] !== "wp-login.php") {

    $delay = 1;  //seconds
    $loader = 'http://devnuru.local/wp-content/uploads/2024/09/devnuru-spinner.svg';
    $overlayColor = '#ffffff';
    echo '<div class="Preloader"><img 

src="' . $loader . '" alt="" style="height: 150px;"></div>

 <style>
.Preloader {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: ' . $overlayColor . ';
  z-index: 100000;
  display: flex;
  align-items: center;
  justify-content: space-around;
}
</style>

<script>
document.body.style.overflow = "hidden";
document.addEventListener

("DOMContentLoaded", () => setTimeout( function() { 

document.querySelector("div.Preloader").remove(); 

document.body.style.overflow = "visible"; } , ' . $delay . ' * 1000));
</script>
';
  }
}

When I’m putting HTML Code in my footer & CSS code in my main CSS file & JS code in JS file then It’s not working.

2

Answers


  1. add loader to header

    add_action('wp_head', 'loader');
    function loader(){
    ?>
       <div class="loader"></div>
       <style>style here</style>
       <script>your code here</script>
    <?php
    };
    
    Login or Signup to reply.
  2. If you don’t mind hard-coding the variable values into your theme:

    For the page:

    <div class="Preloader"><img src="//devnuru.local/wp-content/uploads/2024/09/devnuru-spinner.svg" alt="" style="height: 150px;"></div>
    
    <script>
    document.body.style.overflow = "hidden";
    document.addEventListener
    
    document.addEventListener("DOMContentLoaded", () => setTimeout(() => {
    
        document.querySelector("div.Preloader").remove();
    
        document.body.style.overflow = "visible";
    }, 1000));
    </script>
    

    For the css file:

    .Preloader {
        position: fixed;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: #ffffff;
        z-index: 100000;
        display: flex;
        align-items: center;
        justify-content: space-around;
      }
    

    Don’t forget to reload the script from the source in your browser with a hard refresh.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search