I created a new theme using the Hugo CLI and want to add some Javascript to assets/js/main.js, specifically a function which be called by the onclick event of a button within my header partial, however the function is not found and when I check the file debugger in my browser I notice the code is omitted.
Here’s a simple case to reproduce the behaviour:
// main.js
function hello() {
console.log("Hello World!");
}
hello()
layouts/partials/head/js.html was generated by the template creation and I have not touched.
When I load the final main.js file in my browser I see
// main.js viewed in the Firefox's file bugger
(() => {
// <stdin>
function hello() {
console.log("Hello World!");
}
hello();
})();
but if I comment out the call to hello() the function is removed by the minification step and I see:
// main.js viewed in the Firefox's file bugger
(() => {
})();
while this is expected behaviour for minification, I was wondering
How I can configure my theme to ensure the function remains without removing minification from my site?
Seems reasonable to remove definitions of functions that are never called. If you don’t call them, you don’t need them. So, what’s the point in defining them?
Make sure the function is called or referenced somewhere. And that should not be the onclick attribute of a button element.
There are plenty of use cases for calling javascript from a button’s onclick event, this logging example was purely illustrative.
I am calling said function from the HTML but the javascript pipeline doesn’t see that hence it treats the function as unused. My initial thought would be to add the function from within the javascript by using document.getElementById(...).onclick = hello; or similar.
I was talking about the onclick attribute. If you add a handler with addEventListener, the handler doesn‘t get removed when minifying, in my experience. And addEventListener() is the recommended method since several years now.
Since you don’t show your real code, it’s not possible to tell what’s going on.