Home > OS >  Calling a function in HTML vs in Javascript
Calling a function in HTML vs in Javascript

Time:07-25

I wanted to ask if it makes a difference where I call my function. For example when submitting a form, what is the preferred / better way?

1:

<form id="registerForm" action="javascript:register()">
   <label for="user">Username</label>
   <input id="user" name="user" type="text" />
   ...
   <button>Register</button>
</form>

Or

const registerFormElement = document.querySelector("#registerForm");
registerFormElement.addEventListener("submit", (e) => {
  // some code ...
});

I always used the second approach, but i saw on github that some people use the first code example.

CodePudding user response:

The first approach is easier to understand for beginner. But the second approach is much prefered way for production code.

For production code (on real websites), we generally use obfuscation and minification, which can replace the function name to reduce JS script file size. (e.g.: register function name would be replaced to r after obfuscation and minification).

Hence, it is always better to use second approach.

  • Related