Ask any question about WordPress here... and get an instant response.
How can I enqueue custom scripts in my theme without affecting site performance?
Asked on Nov 15, 2025
Answer
Enqueuing custom scripts in WordPress themes is crucial for maintaining site performance and ensuring compatibility with other plugins and themes. The recommended way to add scripts is by using the `wp_enqueue_script` function in your theme's `functions.php` file.
<!-- BEGIN COPY / PASTE -->
function my_theme_enqueue_scripts() {
// Register the script with a unique handle, file path, dependencies, version, and in_footer flag
wp_register_script('custom-script', get_template_directory_uri() . '/js/custom-script.js', array('jquery'), '1.0.0', true);
// Enqueue the registered script
wp_enqueue_script('custom-script');
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_scripts');
<!-- END COPY / PASTE -->Additional Comment:
- Always use `wp_register_script` before `wp_enqueue_script` for better control over script dependencies and loading.
- Set the last parameter of `wp_register_script` to `true` to load the script in the footer, improving page load times.
- Ensure your script's dependencies (like jQuery) are correctly listed to avoid conflicts.
- Use versioning to manage browser cache effectively by updating the version number when the script changes.
Recommended Links:
