I want to automatically add height
and width
attributes to all my images. It is perfectly done via this nice plugin, but I host my site on GitHub Pages where external plugins are not supported.
Question: How to prefill height/width attributes of an image without using a plugin?
Why do I need this?
My site works well even without height
and width
but I want to specify them because it is important from SEO point of view (you can find some details on its importance here).
2
Answers
This question seems to apply to content images in markdown files. These images have no width or height set by default.
The short answer
You can just set the width and height directly in HTML in your markdown, like this:
The long answer
You cannot retreive the width and height of the image programmatically without a plugin, so when you use (pure) markdown you get an image without a width and height property. The question is WHY you wanted to add a width and a height in the first place. Setting the width and height prevents reflow, but it leaves a big gaping hole while loading. Is that truly better? It certainly does not look nice. Progressive JPG’s are a very nice solution for this problem, but I do not prefer to set the width and height on them, as ‘no image’ looks good, and a progressive JPG also always looks good.
You say you want it for SEO reasons, but I cannot think of any.
If your website is so slow you actually want to interact with content below the image before the reflow, the logical solution is to make your website load faster.
However, if you have users with a really slow connection, you might want to manually add the image to the markdown in HTML. See the short answer for a code example.
Writing an internal filter to do this using the fastimage gem is fairly simple. You can define your filter in the
_plugins
directory of your project (this is outlined in the Jekyll documentation)As a very rough example, you could do something like this:
Which would be used like so:
Of course this still won’t work with GitHub pages directly because custom plugins are not supported. To use custom plugins in general, one solution is to build the site locally and include it in the repository.