0

I have this simple HTML page:

<html>
    <head>
       <script>
       share();
       </script>
    </head>
    <body>
       <script>
          function share() {
                alert('test');
          }
       </script>
   </body>
</html>

I need to call the function share from the <head> and the function itself must be defined in the <body>.

The above code leads to undefined function error.

This is just a simplified script to explain the issue so it needs to be done that way. Is there a way around this?

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Michael Samuel
  • 3,820
  • 12
  • 45
  • 85

3 Answers3

2

You need to wait for the body to be loaded, so

<html>
<head>
   <script>
   window.onload=share;
   </script>
</head>
<body>
   <script>
      function share() {
            alert('test');
      }
   </script>

BReal14
  • 1,603
  • 1
  • 12
  • 35
0

Use

     <html>
        <head>
<script src="jquery-1.11.1.min.js"></script>
           <script>
            $(document).ready(function() {
               share();
            });
           </script>

        </head>
        <body>
           <script>
              function share() {
                    alert('test');
              }
           </script>
Pratik
  • 1,122
  • 8
  • 26
0

You can use

    <html>
    <head>
       <script>
        windows.onload = function(){
           share();
        }
       </script>
    </head>
    <body>
       <script>
          function share() {
                alert('test');
          }
       </script>
</body>
</html>

or you can use Jquery version

  <html>
        <head>
         <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
           <script>
            $(document).ready(function() {
               share();
            });
           </script>
        </head>
        <body>
           <script>
              function share() {
                    alert('test');
              }
           </script>
    </body>
    </html>

Both of them work in this condition however if you want to know the difference between this tow I suggest to see this
window.onload vs $(document).ready()

Community
  • 1
  • 1
Daniel.V
  • 2,322
  • 7
  • 28
  • 58