Scanning for custom embed and prefetching

I have an embed which is essentially a script and a div (so not an oembed) which can easily be added via the html block. I'd like to be able to slip a prefetch link conditionally into the head when someone's used the embed, but not have it in every page by default. I have a solution:

function prefix_filter_embeds( $content ) {
  if strpos( $content, url-we're-looking-for ) !== false ) {
    add_action( 'wp_head', 'prefix_url_actions', 0 );
  }
  return $content;
}

add_filter( 'the_content', 'prefix_filter_embeds' );

function prefix_url_actions() {
  echo 'link rel=prefetch href=etc-etc-etc crossorigin';
}

But I'm not entirely sure this is the smartest or most efficient solution, and I vaguely know WP has some mechanisms for approaching this issue (like wp_resource_hints). Is there a more efficient/appropriate way to solve this issue?

Topic embed the-content wp-head filters hooks Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.