-
Hello,
I’ve searched through the forum but haven’t found a definitive answer about the best practices for adding JavaScript to my website. Specifically, I’m trying to understand:What’s the recommended approach for adding JavaScript code, either globally (across the entire site) or just on specific pages?
I know it’s possible to add inline JavaScript with script tags, but I’ve noticed that this code doesn’t get minified during the build process, which seems inefficient.
Is there a better method for incorporating JavaScript, such as using external .js files that can be properly optimized?
Does the platform/framework offer any built-in solutions for managing JavaScript assets that I might be overlooking?I’d appreciate any guidance on the best approach that balances convenience, performance, and maintainability.
Thanks in advance! -
up
-
Alvind
Hi there,
It depends on how much JS code you need to add. If it’s just a few lines, using an external file might be overkill, and you won’t gain much from a performance perspective.
If you prefer the GeneratePress approach, we recommend adding JS using the Hook Element:
https://docs.generatepress.com/article/hooks-element-overview/This allows you to load the script only on specific pages/posts or site-wide.
A snippet plugin is also an option, depending on your preference.
If you want to use an external file, you’ll need a child theme. Add the JS file to the child theme’s root folder and enqueue it using a function in
functions.php
.Let us know if you have any questions!
-
Hello! Thanks for the clear reply, I understood. My only doubt is: the script that is injected via ‘hook’ is an inline script right?.
-
Alvind
Yes, that is correct. You can still “defer” the script by hooking it to
wp_footer
, so performance-wise, it shouldn’t be a concerning issue. -
ok thanks!
-
Alvind
You’re welcome!
- You must be logged in to reply to this topic.