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');
}
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.I also added
imagesloaded
andlazyload
as dependencies forcd
, which I think is correct. I don’t know ifimagesloaded
is dependent uponlazyload
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.As a corollary to @s_ha_dum’s answer, you could also register scripts with hierarchically declared dependencies, and then just enqueue your ultimate script. Something like so:
Functionally, it really makes no difference; it’s mostly a matter of preference. I like to declare all dependencies explicitly for each script, but this method is a bit more shorthand.
In my case,
cd.js
will wait tilllazyload-1.8.4.js
loaded. But,lazyload-1.8.4.js
won’t wait forimagesLoaded.js
load. So,cd.js
won’t wait forimagesLoaded.js
too, because there is no chain between them.I use this in my code, it works but not so fast.
onLoadInit.js File in GitHub
, i use the same logic.
If you need more speed, I think you should use Promise, CustomEvent