Dynamically create an iframe and attach onload event to it

后端 未结 4 2148
隐瞒了意图╮
隐瞒了意图╮ 2021-02-08 05:20

I have created a iframe dynamically and added a src attribute to it. Then I have appended this iframe to body of the page. Know I want to attach an onload

4条回答
  •  佛祖请我去吃肉
    2021-02-08 06:02

    You can add a load event listener to the iframe's contentWindow, which is just like any other Window.

    Here's an example:

          iframe = document.createElement('iframe')
          iframe.setAttribute('src', 'https://example.com/')
    
          document.getElementsByTagName('body')[0].appendChild(iframe)
          const onLoaded = function() {
            console.log('iframe loaded');
          }
          if (iframe.contentWindow.document.readyState === 'complete') {
            console.log('already loaded')
            onLoaded()
          } else {
            iframe.contentWindow.addEventListener('load', onLoaded)
          }
    

提交回复
热议问题