A Web Component with Different HTML for Desktop and Mobile
Christian Schaefer has written an extensive piece on working with web advertisements. The article first lays out the challenges ads create, then covers modern solutions for each of them.
Among the snippets, one stood out: a straightforward approach to building a component that renders different HTML depending on screen size.
<div class="ad">
<template class="ad__mobile">
// Mobile ad HTML code with inline script
</template>
<template class="ad__desktop">
// Desktop ad HTML code with inline script
</template>
<script>
const isMobile = matchMedia('(max-device-width: 20em)').matches;
const ad = document.currentScript.closest('.ad');
const content = ad
.querySelector(isMobile ? '.ad__mobile' : '.ad__desktop')
.content;
ad.appendChild(document.importNode(content, true));
</script>
</div>
As neat as it is, Schaefer ultimately takes an entirely different approach in the article.
Chris Coyier reworked the same snippet using a custom element, with the JavaScript moved into JavaScript.
See the Pen A Web Component with Different HTML for Desktop and Mobile by Chris Coyier (@chriscoyier) on CodePen.



