The following code shows an Example of onLoad() and onBeforeUnload() in JavaScript.

Basically, the onLoad event fires when user loads a page or refreshes the page by pressing the F5 button. The following example shows that we have a function f1() that gets executed when user opens the page. Similarly, when user clicks on the link present in the page, a warning message appears.

<html>
  <head>
    <title>JavaScript Events</title>
    
  </head>
  <body id="b1" onload="f1()" onbeforeunload="return f2()">

   <a href="http://google.com">Google</a>
<script>
      function f1()
      {
         alert('hi');
      }
      function f2()
      {
         return 0;
      }      
    </script>
  </body>
</html>

Output

Demonstrating an Example of onLoad() and onBeforeUnload() in JavaScript
Demonstrating an Example of onLoad() and onBeforeUnload() in JavaScript

When user tries to navigate away from the abobe page, the onBeforeUnload event fires.

OnBeforeUnload Fires
OnBeforeUnload Fires

Further Reading

Evolution of JavaScript from ES1 to ES2020

Introduction to HTML DOM Methods in JavaScript

JavaScript Practice Exercise

Understanding Document Object Model (DOM) in JavaScript

What is Asynchronous JavaScript?

Understanding JSON Web Tokens

Arrow Functions in JavaScript

Understanding HTTP Requests and Responses

Princites