javascripthtmldom-eventsunobtrusive-javascript

Migrate non function script from HTML to JS file


As a begineer i am facing a problem, i followed an advise from several opinions to keep my HTML file clean, so i created a JS file and started migrating all scripts to a it, everything is Ok until i had to make this in it :

<script>
document.getElementById("mobile-toggle").addEventListener("click",function(){
document.getElementById("mobile-date").innerHTML = "Today is ...";});
</script>

When this script in is my HTML file it is run by the browser automatically but when i put it in the JS file, it simply don't work without being called with a function name, and that's what i want to avoid due to unobtrusive javascript recommendations, so my question is "is there a way to make a script from JS file to be run automatically without a call from HTML event ?

Thanks.


Solution

  • Include your script in the HTML with defer attribute. This will run the code when HTML is ready. You could place the script tag at the end before </body> as well, but I prefer having it on top.

    <head>
       <script src="/myscript.js" defer>
    </head>
    

    in myscript.js

    (function() {
       // your code goes here
    })();
    

    Wrapping this into a function gives your own scope and another wrap into parenthesis and () at the end will do the execution.