Search code examples
javascripteventtrigger

javascript tag trigger - code position on page


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


Solution

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