开发者

javascript tag trigger - code position on page

开发者 https://www.devze.com 2023-04-12 12:57 出处:网络
i use that tag to alert me when a tag has been shows up <html> <head> </head> <body>

i use that tag to alert me when a tag has been shows up

<html>
  <head>
  </head>
  <body>
    <script type="text/javascript">
      document.getElementsByTagName('iframe')[0].onload = function() {
        alert('loaded');
      }
    </script>
    <iframe></iframe>
  </body>
</html>

strange , since this code working :

<html>
  <head>
  </head>
  <body>
    <iframe></iframe>
    <script type="text/javascript">
      document.开发者_JAVA百科getElementsByTagName('iframe')[0].onload = function() {
        alert('loaded');
      }
    </script>
  </body>
</html>

why the Js need to under the tag to work? what's the problem here?


Because the code in a script tag is executed immediately. And in the first example the iframe doesn't exist at that time. But what you can do is to wrap you code into an onload (for the main page) event. E.g.:

window.onload = function() { 
    //your code
}

Then it doesn't matter where the code is placed.


Iframe tag does not exist at the moment you are trying to access it.
You may check that by simply alerting array length, like

alert(document.getElementsByTagName('iframe'));

Have you thought about executing your javascript after the page is loaded? You may use some frameworks like jQuery to facilitate crossbrowser issues. Or just put all your javascript code to the very bottom of body.

0

精彩评论

暂无评论...
验证码 换一张
取 消