A Jekyll plugin to replace img
tags with custom elements during site generation.
It runs a regular expression to find HTML img
tags against the output of each page and replaces matches with a user-defined replacement.
There are a number of custom elements you can use, such as progressive-img
, amp-img
and (my very own) hy-img
.
Note that replacing images during site generation is necessary for lazy-loading, because the browser will start loading any img
tag as soon as it is parsed, before it can be touched by client side code.
- Lazy-loading images increases page load speed and is recommended by Google.
- So you can use the
![alt](src)
syntax for images without polluting your posts with lengthy HTML tags.
-
Add the following to your site's Gemfile:
gem 'jekyll-replace-img'
-
Add the following to your site's config file:
plugins: - jekyll-replace-img
Note: If you are using a Jekyll version less than 3.5.0, use the
gems
key instead ofplugins
. -
Configure and provide your replacement.
You can configure this plugin in _config.yml
under the replace_img
key. The defaults are:
replace_img:
re_img: <img\s*(?<attributes>.*?)\s*/>
re_ignore: data-ignore
replacement: |
<hy-img %<attributes>s>
<noscript><img data-ignore %<attributes>s/></noscript>
</hy-img>
You can set the re_img
key to a custom regular expression to look for image tags (or possibly other tags). Note that the capture groups need to be named and match the names in replacement
. E.g.:
<img\s*(?<attributes>.*?)\s*/>
Mind the use of the non-greedy quantifier (*?
) in the capture group to avoid capturing all images in a single match!
You cannot provide flags and the regular expression is always case-insensitive.
You can provide a custom regular expression on the re_ignore
key that will run against the text matched by the re_img
expression. If it matches, the image will not be replaced.
You cannot provide flags and the regular expression is always case-insensitive. Data URLs are always ignored.
A replacement string for every sequence matched by re_img
but not re_ignore
. Has access to the named captures in re_img
, which is attributes
by default.
Capture groups can be inserted in the replacement like this %<attributes>s
, where attribures
is the name of the capture group and s
is the string tag. See Ruby's sprintf
documentation for more.
<progressive-img %<attributes>s></progressive-img>
<noscript><img data-ignore %<attributes>s/></noscript>
- Allow multiple ignore expressions
- Allow substitutions of matched groups, e.g.
s/width/w