Yuval Sh
Yuval Sh

Reputation: 21

onload on html tag before the script tag

I'm trying to get a function to run when some element on the page is loaded

   <img src="" onload="myfunction()">


   <footer>
    <script src="main.js"></script>
   </footer>

Now, the problem is that the page is trying to load the function before the js file is loaded Do I have a solution other then loading the js file in the header??

Upvotes: 1

Views: 43

Answers (1)

Dan P
Dan P

Reputation: 924

I'd have a tiny function that just waits until the JS file is loaded, and then call the function in the JS file. Example:

<img src="" onload="stateCheck()">

<script>
let stateCheck = setInterval(() => {
  if (document.readyState === 'complete') { // could use = 'interactive' too
    clearInterval(stateCheck);
    myfunction()
  }
}, 100);
</script>

<script src="main.js"></script>

Upvotes: 1

Related Questions