How do I get rid of my inclusion race-condition on wp_enqueue_script

I’m trying not to be a lazy dev. Thus I want to only include my js files where they are needed.

As the js is needed everywhere where my shortcode is used I tried to do what was answered here.

i.e.:

js

function do_cool_stuff(){
//do the most awesomest of stuff
//..ok mostly changes textvalues dynamically
}

php

function enqueueAllMyStuff(){
wp_enqueue_script(‘my_stuff’,path_to_my_stuff);
wp_localize_script(‘my_stuff’,’jabba_the_slug’,[‘url’=>admin_url(‘admin-ajax.php’)];
//…
}
add_shortcode(‘goodName’,__NAMESPACE__.’my_shortcode’)
function my_shortcode(){
enqueueAllMyStuff();
return ‘<script>do_cool_stuff()</script>’;
}

But that did not work. As “do_cool_stuff is not defined”.
Tried to do

return ‘<img src=”‘.admin_url().’/images/loading.gif” onload=”do_cool_stuff()”/>’;

Which works nicely from time to time. Implying its a race condition.

function my_shortcode(){
add_action(‘wp_enqueue_scripts’,__NAMESPACE__.’enqueueAllMYStuff’);
return ‘<script>do_cool_stuff()</script>’;
}

also does not work, as the headers are already send.

so… There ought to be a better way to do this.

Read more here:: How do I get rid of my inclusion race-condition on wp_enqueue_script

Leave a Reply

Your email address will not be published. Required fields are marked *