0

I am trying to delay the loading of a JS script on WordPress for 3 seconds, i.e., I want the page to load and then after 3s load the JS script.

I have tried including "setTimeout" without luck.

<!-- Facebook Pixel Code -->
<script>
  !function(f,b,e,v,n,t,s)
  {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
  n.callMethod.apply(n,arguments):n.queue.push(arguments)};
  if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
  n.queue=[];t=b.createElement(e);t.async=!0;
  t.src=v;s=b.getElementsByTagName(e)[0];
  s.parentNode.insertBefore(t,s)}(window, document,'script',
  'https://connect.facebook.net/en_US/fbevents.js');
  fbq('init', 'xxxxxx');
  fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" style="display:none"
  src="https://www.facebook.com/tr?id=xxxxxx&ev=PageView&noscript=1"
/>
</noscript>
<!-- End Facebook Pixel Code -->
user229044
  • 232,980
  • 40
  • 330
  • 338
Beccas
  • 105
  • 1
  • 2
  • 7

2 Answers2

0

You need to dynamically load the javascript. See this stackoverflow question

I would recommend this answer extended with setTimeout (untested):

<script type="module">
  setTimeout(()=>{
  import('hello.mjs').then(module => {
      module.hello('world');
    });
  }, 3000);
</script>
Taxel
  • 3,859
  • 1
  • 18
  • 40
0

Maybe this will help you. Just put your javascript inside this code.

  document.onreadystatechange = function () {
     if (document.readyState == "complete") {
        setTimeout(function(){ 
          // document is ready. Load your javascript here.
        }, 3000); //javascript will load 3 seconds after your page has fully loaded
     }
 }

onreadystatechange