Is This The Most Efficient Way To Add Javascript Files?

I am currently rewriting an HTML template into a WordPress theme. It has a lot of code dependencies, and I’m wondering if this is the proper, most efficient way to add it. This code is listed in my functions.php file.

//Load Javascript
if (!is_admin()) add_action("wp_enqueue_scripts", "my_scripts");

function my_scripts() {
    wp_register_script('easytabs', get_template_directory_uri() . '/js/jquery.easytabs.min.js', array('jquery'), null, true);
    wp_register_script('respond', get_template_directory_uri() . '/js/respond.min.js', false, null, true);
    wp_register_script('adipoli', get_template_directory_uri() . '/js/jquery.adipoli.min.js', array('jquery'), null, true);
    wp_register_script('fancybox', get_template_directory_uri() . '/js/jquery.fancybox-1.3.4.pack.js', array('jquery'), null, true);
    wp_register_script('isotope', get_template_directory_uri() . '/js/jquery.isotope.min.js', array('jquery'), null, true);
    wp_register_script('gmaps_google', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://maps.google.com/maps/api/js?sensor=false", false, null, true);
    wp_register_script('gmap', get_template_directory_uri() . '/js/jquery.gmap.min.js', array('gmaps_google'), null, true);
    wp_register_script('custom', get_template_directory_uri() . '/js/custom.js', array('gmap'), null, true);

    wp_enqueue_script('jquery');
    wp_enqueue_script('easytabs');
    wp_enqueue_script('respond');
    wp_enqueue_script('adipoli');
    wp_enqueue_script('fancybox');
    wp_enqueue_script('isotope');
    wp_enqueue_script('gmaps_google');
    wp_enqueue_script('gmap');
    wp_enqueue_script('custom');
}

1 Answer
1

This is the proper way to load scripts. Whether it’s effecient will depend on when you actually need to load the scripts. Currently it will load on every front end page. If this is not necessary, you should put some conditionals and call wp_enqueue_scripts when the file is actually needed.

Also if you are loading a script you don’t have to manually queue its dependencies (other scripts it requires to have been loaded to work). For instance wp_enqueue_script('custom'); will automatically load ‘gmaps_google’ and ‘gmap’ as well – so you don’t need to tell WordPress load them.

If you are simply registering, then immediately enqueuing the scripts you can neaten up the code by providing the script’s location (and dependencies etc) in wp_enqueue_scripts and not registering them. However, usually it’s best to register the scripts and then enqueue them only when needed (e.g. in a shortcode or widget callback) depending on the context.

Finally, wp_enqueue_scripts only fires on the front-end so the !is_admin check is superfluous.

Leave a Comment