1
votes

wp_enqueue_script() as I read about so far and went through the source code instantiates new wp_scripts object 'representing' the script.

My question is how does wordpress know when to load the the script source when needed ?

For example, on index I need bootstrap and jquery, I enqueue bootstrap with jquery dependency in functions.php. How does wordpress know to automatically load the bootstrap on the first page ? What I want to understand is the logic behind it.

I have to create a new plugin and I need some scripts for a slideshow, what I want is to create a quality plugin, optimized using wp_enqueue_scripts, but I don't really understand the concept in-depth so I can use it properly (to load the scripts only when the plugin is activated)

1

1 Answers

1
votes

You can treat wp_enqueue_scripts as a kind of action_hook. I.e. when it is time to create pages, it will include the file. You can also make it dependant on another file being loaded, so if jQuery is needed, you can stipulate this in the function and it will load after jQuery. This maintains seperation of your code.

If you want to optimize the code, you can make the function dependant on the page you are loading.

Forexample:

function prepare_scripts() {

    if(is_front_page() )
     wp_enqueue_scripts('myscript', 'path to script', array( 'jquery' ) );

}

add_action( 'wp_enqueue_scripts', 'prepare_scripts' );

As @knoblik suggests, you can set the priority for the add_action() if needed. This will probably enqueue the script in the order of the priority.