How to include javascript only on pages that contain images?

How to include javascript only on pages that contain images?

Is it possible to include javascript (for lazy loading images) only on pages that contain images?

If it’s possible, then how can I do this?

For videos I use the following:

---
videos: true
---

{{- with .Params.videos -}} <script> here's the script </script> {{ end }}

There not many pages with videos on it.

But most pages contain images and actually I do not want to include the frontmatter line on all those pages.

Is there no easier way to do this for pages with images on it? (e.g., with config.toml)

Haven’t tried but, maybe you could use in on .Content in the <head> of your single?

{{ if in .Content "img" }}thescript{{ end }}

Edit - the key is finding what should be searched. Also, if you’re adding images via a shortcode you can try .HasShortcode.

Thank you Rick. Will try it.

UPDATE: Not working. It will remove the script from all pages.

Maybe in is not adapted for string, though I thought it was. You could try strings.Contains

1 Like

This doesn’t answer your question precisely, but I think it will get you what you’re after.

Instead of explicitly calling a script where there are images, there’s a lightweight script I use called “lazysizes” https://github.com/aFarkas/lazysizes One if its plugins noscript allows you to wrap assets and lazyload them without manipulating the image itself https://github.com/aFarkas/lazysizes/tree/gh-pages/plugins/noscript

So, you could either add the noscript code around your .Content or from within a shortcode. The entire thing (primary script + noscript plugin) is about 5kb gzipped.

Hope that helps!

2 Likes