Question

I'm working on a multisite instalation, that will have several subsites and i'm in doubt about how to organize my js files.

The WP Theme Handbook

says that js files should go inside the assets folder.

So as each subsite will have different js scripts, i assume its correct to make a .js file for each site.

My question is if its a good idea to make multiple js files per site, since there are some scripts that will run only on specific custom templates. I ask this because if i did this many of my js files would have only one function inside.

The file structure would be something like this:

Root
-assets
--js
---site1js
----script1.js
----script2.js
----script3.js

---site2js
----scripts.js

Does this affect the performance of the site? Or its just a bad pratice and i should put all the scripts together?

Also, does it apply to css as well?

Thanks

Was it helpful?

Solution

Generally speaking, combining all of the global scripts will boost performance, but so will enqueueing JS selectively - meaning if a script is only used on one CPT or template, you should only enqueue it there.

Look into conditionally enqueueing JS in your functions.php. You can target specific sites by blog_id and target specific post types, templates, etc. If some of your JS is very short, you can also add an inline script rather than serving a separate file. For example:

function wpse_306134_enqueues() {
    // enqueue the sitewide theme script file
    wp_enqueue_script('wpse-scripts', get_template_directory_uri() . '/wpse.min.js', array('jquery'), '1.23', true);
    // enqueue an inline script only on the 'about' page
    // adjust this condition as needed: if is_singular, etc.
    if(is_page('about')) {
        wp_add_inline_script('wpse-scripts', '(function($){jQuery(document).foundation();})(jQuery); jQuery(".gallery-icon a").swipebox();');
    }
}
add_action('wp_enqueue_scripts', 'wpse_306134_enqueues');

Personally, I would put all my JS files in a single folder and name them by blog_id if that applies. It may make sense to have a global JS, then site-specific ones, and then these additional inline enqueues for small snippets that don't apply to most URLs.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top