There are at least two reasons not to put the functions directly in the HTML:
Performance in loading the web :
If you have a web page that is updated to each call (or every X time) because it is generated dynamically (PHP or JSP or ASP or similar technologies), it is not cacheable. You will have to download the lines of code and HTML every time you want to see the page. If in addition the functions that you use are not only specific to that page and you want to reuse them as you navigate through your application, in each load you will have to download them again. Instead, having a "static" file with all that code, the browser can cache it and you save the load.
Clarity : When we write code, we almost always end up using a pattern of the MVC type (model, view and controller), separating our application in layers. If we focus on our view in web format, we can divide it again into three similar layers:
- Model: HTML (what it looks like).
- View: CSS files (how it looks).
The maintenance of the code is simpler as well since a designer could take care of the CSS as soon as we give him the HTML and the style book of the application while a front-end developer could write the necessary calls to the back-end in a file without having to deal with the back-end code (knowing only the API). Besides, debugging the code is much more comfortable as well.
I would also avoid things like
Always adding the behavior entirely in the js file: