When is it too late to call the action wp_enqueue_scripts?

I’m creating a plugin that always enqueues a script in the footer. I also have a function that if called would enqueue an additional script that depends on the other one. Here is the basic format of my plugin…

<?php
class MyPlugin {
    public function __construct() {
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
    }

    public function enqueue_scripts() {
        wp_enqueue_script('myscript', plugins_url('js/myscript.js', __FILE__), array('jquery'), null, true);
    }

    public function api() {
        add_action('wp_enqueue_scripts', array($this, 'api_scripts'));
    }

    public function api_scripts() {
        wp_enqueue_script('api', plugins_url('js/api.js', __FILE__), array('myscript'), null, true);
    }
}
$_GLOBALS['myplugin'] = new MyPlugin();

In my theme’s functions.php file I would like to know when I can make a call to enqueue the script. I’ve tried attaching to plugins_loaded, but the script is not called.

<?php
function myfunction() {
    global $myplugin;
    $myplugin->api();
}
add_action('plugins_loaded', 'myfunction');

Related posts

1 comment

  1. The function wp_enqueue_scripts— with an ‘s’– is used as a callback to wp_head. All that the function wp_enqueue_scripts does is fire the wp_enqueue_scripts action. So the last time that you would be able to use the action wp_enqueue_scripts is before the wp_enqueue_scripts callback on the wp_head hook.

    In terms of theme templates, that means you need to hook it in before get_header, or on a hook that runs early enough in the hook sequence fired as a consequence.

    Couple of notes:

    1. It is $GLOBAL not $_GLOBALS— inconsistent, I know.
    2. It works perfectly fine if not hooked to plugins_loaded. That is, just this in the theme’s functions.php: global $myplugin; $myplugin->api();. I can’t say that I know why the hooked version doesn’t work. I’d guess it is simply too early but would have to do some research to workout the mechanics. after_setup_theme works and so does wp_loaded

Comments are closed.