Load multiple Javascript scripts

I have three Javascript script that I need to load –

  • imagesLoaded.js
  • lazyload-1.8.4.js
  • and cd.js

cd.js contains my functions that use imagesLoaded.js and lazyload-1.8.4.js.

Do load them altogether or separately?

function add_my_script() {
  wp_enqueue_script(
    'imagesLoaded',
    get_template_directory_uri() . '/js/imagesLoaded.js', 
    array('jquery'),
    'lazyload',
    get_template_directory_uri() . '/js/lazyload-1.8.4.js',
    array('jquery'),
    'cd',
    get_template_directory_uri() . '/js/cd.js',
    array('jquery')                     
  );
}   
add_action( 'wp_enqueue_scripts', 'add_my_script' );

Code that Worked

            add_action( 'wp_enqueue_scripts', 'add_my_script' );

            function add_my_script() {
                wp_register_script('imagesLoaded',get_template_directory_uri() . '/js/imagesLoaded.js', array('jquery'),true);
                wp_register_script('lazyload',get_template_directory_uri() . '/js/lazyload-1.8.4.js', array('jquery'),true);
                wp_register_script('cd',get_template_directory_uri() . '/js/cd.js', array('jquery','imagesLoaded','lazyload'),true);
                wp_enqueue_script('imagesLoaded');
                wp_enqueue_script('lazyload');
                wp_enqueue_script('cd');
            }

3 Answers
3

I formatted that code as best I could, and once formatted it is obviously very broken. wp_enqueue_script takes 5 parameters. You have 9. And several of the first five are wrong. I expect that you would see errors if you had debugging enabled.

You seem to be trying to enqueue all of your scripts in the same wp_enqueue_script. You can’t do that. Perhaps that is what you are asking, but the question isn’t terribly clear.

function add_my_script() {
  wp_enqueue_script(
    'imagesLoaded',
    get_template_directory_uri() . '/js/imagesLoaded.js', 
    array('jquery')
  );
  wp_enqueue_script(
    'lazyload',
    get_template_directory_uri() . '/js/lazyload-1.8.4.js',
    array('jquery')
  );
  wp_enqueue_script(
    'cd',
    get_template_directory_uri() . '/js/cd.js',
    array('jquery','imagesLoaded','lazyload')                     
  );
}   
add_action( 'wp_enqueue_scripts', 'add_my_script' );

I also added imagesloaded and lazyload as dependencies for cd, which I think is correct. I don’t know if imagesloaded is dependent upon lazyload or the other way around but if you are going to register/enqueue (as you should) then make proper use of the dependency juggling. That is one of the best things about the system.

Leave a Comment