Reputation: 21
I've been trying to figure out what the Elementor (and Elementor Pro) plugins in Wordpress are doing to get their Scripts to load very last in the body, because my plugin Script needs to load AFTER those. It needs to load right before the end body tag.
<script type='text/javascript' src='https://example.com/wp-content/plugins/elementor/assets/lib/swiper/swiper.jquery.min.js?ver=4.4.3'></script>
<script type='text/javascript'>
/* <![CDATA[ */
var elementorFrontendConfig = {"isEditMode":"","is_rtl":"","breakpoints":{"xs":0,"sm":480,"md":768,"lg":1025,"xl":1440,"xxl":1600},"urls":{"assets":"https:\/\/example.com\/wp-content\/plugins\/elementor\/assets\/"},"settings":{"page":[],"general":{"elementor_global_image_lightbox":"yes","elementor_enable_lightbox_in_editor":"yes"}},"post":{"id":406,"title":"Chat","excerpt":""}};
/* ]]> */
</script>
<script type='text/javascript' src='https://example.com/wp-content/plugins/elementor/assets/js/frontend.min.js?ver=2.2.1'></script>
</body>
</html>
I've tried increasing the priority for my enqueue scripts:
add_action( 'wp_enqueue_scripts', 'ajax_chat_enqueue_scripts',999999,1);
And I'm enqueueing in the footer with 'footer=true' at the end:
wp_enqueue_script( 'chat-post', plugins_url( '/chat-post.js', __FILE__ ), null, null, true );
But still my script won't show up AFTER the frontend.min.js script.
I've Googled this topic but I end up with the same answers about how to get your script in the footer. There's nothing about what the hell Elementor is doing to force their scripts to the bottom.
I found a solution: enqueue my scripts in my plugin like this:
add_action( 'elementor/frontend/after_enqueue_scripts', 'ajax_chat_enqueue_scripts', 999999, 1);
But that just seems like a hack. I would love to solve it with the 'wp_enqueue_scripts' tag.
Upvotes: 2
Views: 7435
Reputation: 225
If your script is depend on other script or scripts and must be inserted after those scripts to work correct, in wordpress you can use wp_enqueue_script() and pass array of dependencies(The 3rd parameter in wp_enqueue_script called $deps) that your script depends on, to this method.
wp_enqueue_script( string $handle, string $src = '', array $deps = array(),
string|bool|null $ver = false, bool $in_footer = false )
example:
wp_register_script('myScript', get_template_directory_uri() . '/javascripts/myscript.js',
array('jquery','bootstrap'), null, true );
In above example myscript is depends on jquery and bootstrap scripts.
Or for any reason if you want insert script after another, try this:
function my_scripts() {
wp_register_script('myscript', get_template_directory_uri() . '/javascripts/myscript.js', null, null, true );
wp_enqueue_script('myscript');
}
add_action( 'wp_enqueue_scripts', 'my_scripts', 20, 1)
play and change $priority parameter of add_action method for wp_enqueue_scripts hook
Upvotes: 1