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
  • 174,715
  • 42
  • 343
  • 413
Michael Samuel
  • 3,390
  • 9
  • 36
  • 78

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>

briansol
  • 1,583
  • 1
  • 11
  • 33
2

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,081
  • 5
  • 21
  • 51
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,116
  • 7
  • 21