简体   繁体   中英

Lazy Loading external javascript

I am using a javascript that's load iframe on the website. i want to lazy load that script. i tried async or defer and loading dynamically but it doesn't load 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 class="editorskit-no-mobile"></div> 

and then, a simple createElement and appendChild

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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