简体   繁体   English

延迟加载外部 javascript

[英]Lazy Loading external javascript

I am using a javascript that's load iframe on the website.我正在使用在网站上加载 iframe 的 javascript。 i want to lazy load that script.我想延迟加载该脚本。 i tried async or defer and loading dynamically but it doesn't load iframe.我尝试了asyncdefer并动态加载,但它不加载 iframe。 is there any way to load this script lazy or after a few seconds.有什么方法可以延迟或几秒钟后加载此脚本。

<div class="editorskit-no-mobile">
<script src="//idx.diversesolutions.com/scripts/controls/Remote-Frame.aspx?MasterAccountID=1606&amp;SearchSetupID=41&amp;LinkID=474907&amp;Height=2000"></script>
</div> 

a very simple solution from your code, leave the <div> without content一个非常简单的代码解决方案,让<div>没有内容

<div class="editorskit-no-mobile"></div> 

and then, a simple createElement and appendChild然后,一个简单的createElementappendChild

<script>
  var divElm = document.querySelector('.editorskit-no-mobile')
  setTimeout(function() {
    appendScript(divElm)
  }, 2000) // 2 seconds

  var appendScript = function(elm) {
    var s = document.createElement('script')
    s.src = '//idx.diversesolutions.com/scripts/controls/Remote-Frame.aspx?MasterAccountID=1606&amp;SearchSetupID=41&amp;LinkID=474907&amp;Height=2000'
    s.type = 'text/javascript'
    s.async = !0
    elm.appendChild(s)
  }
</script>

this way, you are creating the <script> tag on the fly, without loading anything until it actually appends it into the DOM...这样,您正在动态创建<script>标记,而无需加载任何内容,直到它实际将其附加到 DOM 中......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM