Answer the question
In order to leave comments, you need to log in
How to connect the necessary JS-modules on separate pages (CMS Wordpress)?
Is it possible to achieve such an organization of the code, where for each page its own modules are loaded (I implement the "Module" pattern in js). For example, I need an image module (declared in app/image.js) on the www.site.com/images page, but it's not needed on the other pages. Is it possible to specify in WordPress that one set of JS modules needs to be loaded on some pages, and another set on others.
Sorry for the vague wording, but I can provide clarifications if needed.
Answer the question
In order to leave comments, you need to log in
Yes. We make an is_page() check or similar and connect the desired script.
1) Register the script in the theme's functions.php file:
add_action('init', 'framework_register_scripts');
function framework_register_scripts() {
wp_register_script('printcoupon', get_template_directory_uri() . '/js/printcoupon.js', array('jquery'), '1.0.0', true);
}
wp_enqueue_script( 'printcoupon' );
Option 1 (via wp):
Js scripts can be connected using the standard wp_enqueue_script function ( https://wp-kama.ru/function/wp_enqueue_script #4 conditional connection example), in addition to specifying connection conditions, you can specify dependencies that you also need connect and, as far as I remember, minifies scripts (but this is not accurate).
Option 2 (through the main js, which connects to all pages):
In js files can be loaded conditionally through js itself: the connection condition is checked (the presence of the necessary tag or the required url) and the script tag is added with the necessary url. It is better to use third-party libraries for the correct connection, and even better organize the assembly of js through webpack and loading modules through require.ensure.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question