Enqueue script only if page has an oembed

Well the first thing to consider is that the wp_enqueue_scripts action hook fires before the filters on the page/post content are run.

So I would add a function to the wp action hook and test the content for oembeds there.

add_action( 'wp', 'your_oembed_test_function' );
function your_oembed_test_function(){
    //earliest reliable hook to get $post variable
    global $post;

    //do your tests with $post content

    if( $oembed_exists_results ) wp_enqueue_script( $your_handle );

}

Because WP fires before wp_enqueue_scripts you will be able to choose which scripts/styles you want to show based on which oembeds you find in the content.

Leave a Comment