0

I am making a multipage website. I add this preloader to my index page only. I don't get errors in index pages but get many errors on my other pages for this.

The errors i found: main.js:10 Uncaught TypeError: Cannot set property 'textContent' of null Here :

function loader(success) {
  document.body.style.overflowY = 'hidden';

  let time = window.onload;
  let obj = document.querySelector('.preLoader'),
    inner = document.querySelector('.preLoader .count');
  let w = 0,
    t = setInterval(function() {
      w = w + 1;
      inner.textContent = w + '%';
      if (w > 99) {
        obj.classList.add('loaded');
        document.body.style.overflowY = 'auto';
        clearInterval(t);
        w = 0;
        if (success) {
          return success(t);
        }
      }
    }, time);
}
loader();
<!--    PRELOADER    -->
<div class="preLoader t_center g_center fixed" id="preLoader">
  <div class="count">%</div>
</div>
I_love_vegetables
  • 1,575
  • 5
  • 12
  • 26
Deauther
  • 1
  • 1

1 Answers1

0

The error message is telling you that your inner variable has been set to null instead of the reference to the <div> element that you are expecting. This happens when document.querySelector('.preLoader .count') doesn't match anything, which will be the case on the web pages where you don't include your preloader.

You can avoid the problem by checking the value of inner is not null before you use it:

if (inner) {
    inner.textContent = w + '%';
}
JRI
  • 1,766
  • 13
  • 25