Skip to content

Instantly share code, notes, and snippets.

@JakeSteam
Created November 30, 2024 18:03
Show Gist options
  • Save JakeSteam/3b40651a3079ff221243525b3ad843f1 to your computer and use it in GitHub Desktop.
Save JakeSteam/3b40651a3079ff221243525b3ad843f1 to your computer and use it in GitHub Desktop.
How to add automatic webp post banners to Jekyll for faster load times
...
<a class="post-link" href="{{ post.url | relative_url }}">
{% include custom/webp.html path=post.image alt=post.title %}
</a>
...
...
<a href="{{page.image}}">
{% include custom/webp.html path=page.image alt=page.title %}
</a>
...
...
.bg-img {
height: 180px;
border-radius: .17rem;
display: block;
overflow: hidden;
}
.bg-img img {
width: 100%;
height: 100%;
object-fit: cover;
}
...
{% assign path = include.path %}
{% assign alt = include.alt | default: "article" %}
{% assign image_parts = path | split: '.' %}
{% assign extension_length = image_parts | last | size | plus: 1 %}
{% assign base_path_length = path | size | minus: extension_length %}
{% assign base_path = path | slice: 0, base_path_length %}
{% assign webp_path = base_path | append: '.webp' %}
{% assign webp_exists = site.static_files | where: "path", webp_path | first %}
<picture class="bg-img">
{% if webp_exists %}
<source type="image/webp" srcset="{{ webp_path }}" >
{% endif %}
<img src="{{ path }}" alt="Preview image of {{ alt | escape }}" />
</picture>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment