Attaching advanced DOM event handlers
Sometimes we simply want to run JavaScript code when the page loads, rather than in response to an action taken by the user (as in the previous example).
A simple way to achieve this would be to put our code directly in the JavaScript file outside of any functions or event handlers. Using this method, our code would just be executed straight after it is loaded. If we are following the best practice technique of loading our script files at the end of the body tag, our code will be executed after the main body content of the page has loaded.
Note that Moodle implements this best practice for us automatically when we use the technique from the Loading a JavaScript file recipe in Chapter 1, Combining Moodle and JavaScript unless we specify otherwise, as per the Loading a JavaScript file in the <head> recipe. Using this latter technique of loading a script file from the <head>
, our code would be executed before the rest of the page had finished...