I have a Tumblr Site where the width of each post is determined by a tag.
If a post is tagged with #width200
, the css class .width200
is assigned.
The problem is, though the posts have different widths, they all load the same size photo using the theme operator: {{PhotoURL-500}}
.
This works, but for the smaller photos, it's a waste of bandwidth. I could use the theme operator {{PhotoUrl-250}}
but this makes larger photos look bad.
Is there any way around this using theme operators or javascript?
This creates the images on the fly, depending on the hashtag (use #s0
, #s1
, #s2
instead of #width200
, it's easier)
This defaults to a 400px-wide image when Javascript is not available (and for bots like Google and Facebook)
{block:Posts}
{block:Photo}
<script id="{PostID}-image" data-images="{PhotoURL-250},{PhotoURL-400},{PhotoURL-500},{PhotoURL-HighRes}" data-classes="{TagsAsClasses}">
(function () {
//select current script tag
var el = document.getElementById("{PostID}-image");
//get data, this works in IE too
var sizes = el.getAttribute('data-images').split(',');
var classes = el.getAttribute('data-classes');
//figure out which one is selected.
//use hashtags like "#s1",
//where 1 is the index of the url in data-images:
//0 = 250, 1 = 400, 2 = 500, 3 = highres
var imageIndex = classes.match(/\bs(\d)\b/);
if (!imageIndex) {
imageIndex=[0,"0"];//no hashtag found, default to smallest image size
}
//create image and append it after the script tag
var img = new Image();
img.src = sizes[imageIndex[1]];
el.parentNode.insertBefore(img, el.nextSibling);
} ());
</script>
<noscript><img src="{PhotoURL-400}" alt=""></noscript>
{/block:Photo}
{/block:Posts}
I haven't tested this, but you get the idea. If you find bugs, please edit/fix my answer.