JSFiddle - React, Tailwind, and code Playground

web component experiment

by Travis Almand

HTML

<img-srcset src="237" alt="best doggo"></img-srcset>

CSS

html,
body {
  margin: 0;
  padding: 0;
}

JavaScript

class ImgSrcset extends HTMLElement {
  constructor() {
    super();

    const shadow = this.attachShadow({mode: 'open'});
    const src = this.getAttribute('src');
    const alt = this.getAttribute('alt');
    
    let image = document.createElement('img');
    var style = document.createElement('style');
    
    image.alt = alt;
    image.className = 'img-srcset';
    image.srcset = `
    	https://i.picsum.photos/id/${src}/320/240.jpg 320w,
      https://i.picsum.photos/id/${src}/640/480.jpg 640w,
      https://i.picsum.photos/id/${src}/800/200.jpg 800w
    `;
    
    style.textContent = `
    	.img-srcset { width: 100%; opacity: var(--opacity, 1); }
    `;
    
    shadow.appendChild(style);
    shadow.appendChild(image);
  }
}

customElements.define('img-srcset', ImgSrcset);