I’m using the FitVids.js script to make YouTube video embeds work with a responsive layout. The script is < 3kb, but only about half of my pages actually have YouTube embeds.
In terms of total load-time for a page that doesn’t contain a YouTube video, is it more costly to do a strpos()
on the content or to include the script regardless?
I imagine this has a lot to do with the end-user’s connection speed vs. the server’s resources, and honestly, it’s a low-traffic site with undemanding users so it really doesn’t matter… I’m mostly asking because I don’t have a good grasp of performance optimization and I want to learn.
What happens on the userâs side is off topic as @bungeshea said already. Once the user has loaded the file it will stay in the browser cache for a while, so you donât have to worry about double loaded files anyway.
But letâs look at the server side and how WordPress handles this.
If you want to load a script on every page you just hook into
wp_enqueue_scripts
:Dead simple.
If you want to load the script only if there is a YouTube video, you have to hook into
the_content
, search for URLs with a host nameyoutube.com
oryoutu.be
, check ifWP_Embed::autoembed
is activated (this converts URLs into embeds) and load the script if all these conditionals evaluate toTRUE
.This is slower. It is not very safe too: the default handler for videos might be overridden and run later than your content parser.
So: yes, there is a difference. I would use the simple method in your situation. If just 1% of all posts had a video ⦠well this would be a different situation. I would hook into
save_post
then and update a custom meta valueload_fitvid
. On the front-end Iâd test that value (much faster) and load the script then. But this is rather difficult to implement with existing posts.