General developer forum

Run javascript function on page load

 
Picture of Mahtab Hussain
Run javascript function on page load
 
May you live in peace!

I am a Moodle developer. I am upgrading a plugin and have stuck into an issue regarding Javascript.
I have some Javascript code inside the plugin in a separate file. In that file I have defined a function which I want to run when page has been loaded. So, I wrote following line near the end of Javascript file:
window.onload = function() { initmiccheck(); }
I called my Javascript file from within PHP using following line:
$PAGE->requires->js('/mod/quiz/accessrule/mictest/js/recordmp3.js');
I used Javascript 'alert' to check if my Javascript file is loading fine or not. The file appears loading as I do get the alert.
Then, I called my initmiccheck() function from developer tools console in Chrome. The function runs and works perfect.

The issue is that my window.onload is not working as expected because the function initmiccheck() function does not fire on page load.

Can anyone guide what wrong I am doing with the onload statement?

Thanks in anticipation.
Warm regards,

Mahtab Hussain
I have called the javascript


 
Average of ratings: -
Picture of Justin Hunt
Re: Run javascript function on page load
Particularly helpful MoodlersPlugin developers

I think something else is also using onload event and overwriting your function. I think you should use addEventListener to ensure this doesn't happen.

window.addEventListener("load", initmiccheck, false);

 
Average of ratings: Useful (2)
Picture of Mahtab Hussain
Re: Run javascript function on page load
 

May you live in peace Justin!

Thanks for the tip. It worked.

Warm regards,

Mahtab Hussain

 
Average of ratings: -