延迟加载JS脚本

时间:2019-08-23 01:31:03

标签: javascript wordpress delay

我试图将JS脚本在WordPress上的加载延迟3秒钟,即我希望页面加载,然后在3秒钟后加载JS脚本。

我已经尝试过在没有运气的情况下加入“ setTimeout”。

<!-- 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 -->

2 个答案:

答案 0 :(得分:0)

您需要动态加载JavaScript。 参见this stackoverflow question

我建议将此答案扩展为setTimeout(未测试):

<script type="module">
  setTimeout(()=>{
  import('hello.mjs').then(module => {
      module.hello('world');
    });
  }, 3000);
</script>

答案 1 :(得分:0)

也许这会对您有所帮助。只需将您的JavaScript放在此代码中即可。

  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

相关问题