Are you a GenerateCustomer?

Do you have an active GP Premium or GenerateBlocks Pro license key?

Create a GenerateSupport account for GeneratePress and GenerateBlocks support in one dedicated place.

Create an account
Already have a GenerateSupport account? Login

Just browsing?

Feel free to browse the forums. Support for our free versions is provided on WordPress.org (GeneratePress, GenerateBlocks).

Want to become a premium user? Learn more below.

Best way to add custom code snippet

  • 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!

  • 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?.

  • 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.

  • You’re welcome!

Viewing 7 posts - 1 through 7 (of 7 total)
  • You must be logged in to reply to this topic.