Responsive images inside of post content

Thx Kevin!

I now have a solution like this:
post.hbs

{{#post}} 
  <section class="post__content">
    <noscript>
      {{content}}
    </noscript>
  </section>
 
  <script src="{{asset "built/post-content.js"}}"></script>
  {{/post}}

This will load all content normally when JavaScript is disabled and performs the manipulation to use responsive images when JavaScript is enabled with the following code:

post-content.js

function generateResponsiveImage(url) {
  const urlSplit = url.split("content/images");
  const start = "/content/images/size/";
  const end = urlSplit[1];
  return `srcset="${start}w100${end} 100w,
            ${start}w300${end} 300w,
            ${start}w600${end} 600w,
            ${start}w1000${end} 1000w"
    sizes="(max-width: 1000px) 400px, 700px"
    src="${start}600w${end}"
    `;
}

function improvePostPerformance() {
  const contentSection = document.querySelector(".post__content");
  let content = contentSection.querySelector("noscript").innerHTML;

  const images = content.match(/<figure.+?figure>/g);
  const updatedImages = images.map(image => {
    const src = /src="([^"]*)/.exec(image)[1];
    if (src.split("/")[1] === "content") {
      return image.replace(/src="[^"]*"/, generateResponsiveImage(src));
    } else {
      return image;
    }
  });

  images.forEach((image, index) => {
    content = content.replace(image, updatedImages[index]);
  });

  contentSection.innerHTML = content;
}

improvePostPerformance();

It works well, even though it is probably not the most elegant solution.
I will follow this up with a blog post soon :slight_smile:

Thanks for the help on this.

Regarding your problem: Would the image resizer not automatically create the new image sizes when changing the theme as long as the original image is present?
Might be a feature that could slowly transition from opt-in to opt-out on the post page?

Good luck with this.

4 Likes