1

When I want to execute a script myFunction(){} when a page is loaded I have two choices.

1 <body onload="myFunction()">
2 <script> window.onload = myFunction </script>

My question is why we need parentheses in the first case but not in the second case? What is the theory behind it?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Alex
  • 81
  • 6

2 Answers2

0

The attribute version dates back to the early days of Javascript and is not advanced enough to support the notion of referencing a function rather than stating a script fragment to evaluate. Its usage is frowned on nowadays by those who advocate modern Javascript techniques.

Paul Kienitz
  • 878
  • 6
  • 25
0
<body onload="myFunction()">

is a function call: when the page is loaded, the function is called.

<script> window.onload = myFunction </script>

is a reference to the function object. It is a better solution, if only because inline javascript is irritating to read, with its mix of HTML and javascript, while scripts can be separately written and managed.

boisvert
  • 3,679
  • 2
  • 27
  • 53