Support » Plugins » Conditionally Adding Scripts and Styles after "wp_enqueue_scripts" still ok?

  • This question is similar to https://wordpress.org/support/topic/conditionally-adding-scripts-and-styles-if-shortcode-present-1?replies=2, but I’m looking for an updated response, or possibly to update the documentation to clarify the current status.

    Regarindg the function wp_enqueue_script, the docuemntation at https://developer.wordpress.org/reference/functions/wp_enqueue_script says

    The function should be called using the wp_enqueue_scripts action hook if you want to call it on the front-end of the site, like in the examples above. To call it on the administration screens, use the admin_enqueue_scripts action hook. For the login screen, use the login_enqueue_scripts action hook. Calling it outside of an action hook can lead to problems, see the ticket #11526 for details.

    However, before ticket 11526 was created, ticket 9346 allowed you to enqueue scripts for the footer AFTER the scripts in the header had already been outputted. See https://core.trac.wordpress.org/ticket/9346

    So is it “doing it wrong” to enqueue scripts after the scripts have already been outputted in the head?

    And enqueueing styles is another issue: is it ok to enqueue styles after they’re normally outputted in the head? I see this function in class.wp-styles.php:

    public function do_footer_items() { // HTML 5 allows styles in the body, grab late enqueued items and output them in the footer.
            $this->do_items(false, 1);
            return $this->done;
        }

    Implying it’s ok to output css after the head, but only for html5.

    So my understanding is that scripts CAN be enqueued after “wp_enqueue_scripts” but they are of course limited to appearing in the footer. And styles CAN also be enqueued after “wp_enqueue_scripts” but there might be a sub-optimal user expeirence (eg the page might begin unstyled).

    If that’s right, can someone update the developer.wordpress.org doc?

  • The topic ‘Conditionally Adding Scripts and Styles after "wp_enqueue_scripts" still ok?’ is closed to new replies.