Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="result"></div>
              
            
!

CSS

              
                
              
            
!

JS

              
                const heatMap = document.createElement("div");
heatMap.id = "heatMap";
heatMap.style.position = "absolute";
heatMap.style.top = "0px";
heatMap.style.left = "0px";
document.body.appendChild(heatMap);

// https://github.com/GoogleChrome/web-vitals/blob/main/src/lib/getSelector.ts
const getName = (node) => {
  const name = node.nodeName;
  return node.nodeType === 1
    ? name.toLowerCase()
    : name.toUpperCase().replace(/^#/, "");
};

const getSelector = (node, maxLen) => {
  let sel = "";

  try {
    while (node && node.nodeType !== 9) {
      const el = node;
      const part = el.id
        ? "#" + el.id
        : getName(el) +
          (el.className && el.className.trim().length
            ? "." + el.className.trim().replace(/\s+/g, ".")
            : "");
      if (sel.length + part.length > (maxLen || 100) - 1) return sel || part;
      sel = sel ? part + ">" + sel : part;
      if (el.id) break;
      node = el.parentNode;
    }
  } catch (err) {
    // Do nothing...
  }
  return sel;
};

function calculateByteSizes(target, options = {}) {
  // Get all the elements in the target element.
  let elements = Array.from((target || document).querySelectorAll("*"));

  // Filter elements by including/excluding them from the calculation.
  if (typeof options.include === 'function') {
    elements = elements.filter((element) => options.include(element));
  }
  if (typeof options.exclude === 'function') {
    elements = elements.filter((element) => !options.exclude(element));
  }

  // Calculate the byte size of each element.
  const byteSizes = elements.map((element) => {
    // Serialize the element into a string.
    const elementString = new XMLSerializer().serializeToString(element);
    // Calculate the byte size of the string.
    const byteSize = new Blob([elementString]).size;
    return byteSize;
  });

  // Gather data into a single result object for other functions to analyze.
  const data = elements.map((element, index) => ({
    element,
    byteSize: byteSizes[index],
    selector: getSelector(element),
  }));

  // Sort by byte size, from largest to smallest.
  data.sort((a, b) => a.byteSize > b.byteSize ? -1 : 1);

  return data;
}

function generateHeatMap(data) {
  const byteSizes = data.map(d => d.byteSize);

  // Normalize the byte sizes to a scale of 0 to 1.
  const maxByteSize = Math.max(...byteSizes);
  const minByteSize = Math.min(...byteSizes);
  const normalizedByteSizes = byteSizes.map(
    (byteSize) => (byteSize - minByteSize) / (maxByteSize - minByteSize)
  );

  // Create a new div element for each element, and set its background color and position based on its byte size.
  data.forEach(({ element }, index) => {
    const opacity = normalizedByteSizes[index] * 0.5;
    const div = document.createElement("div");
    div.style.backgroundColor = `rgba(255, 0, 0, ${opacity})`;
    div.style.position = "absolute";
    div.style.width = `${element.offsetWidth}px`;
    div.style.height = `${element.offsetHeight}px`;
    div.style.top = `${element.offsetTop}px`;
    div.style.left = `${element.offsetLeft}px`;
    heatMap.appendChild(div);
  });
}

// const data = calculateByteSizes();
// const topLevelElements = [...document.body.children];
// let filteredData = data.filter(({ element, byteSize, selector }) => {
//   // Ignore HTML and BODY elements.
//   return !['HTML', 'BODY'].includes(element.tagName)
//     // Only include the HEAD and top-level children of BODY.
//     && (element.tagName === 'HEAD' || topLevelElements.includes(element))
//   ;
// });
// console.log(filteredData);
// generateHeatMap(filteredData);

function sum(result, { byteSize }) {
  return result + byteSize;
}

// What makes the header so big?
const target = document.querySelector('header');

const header = calculateByteSizes(target);
console.log('Header:', header.reduce(sum, 0));

const exampleElements = calculateByteSizes(target, {
  include: (element) => element.classList.contains('example'),
});
console.log('Example Elements:', exampleElements.reduce(sum, 0));

const everythingElse = calculateByteSizes(target, {
  exclude: (element) => element.classList.contains('example') || element.closest('.example'),
});
console.log('Everything else:', everythingElse.reduce(sum, 0));

// Header          | 1117KB
// Examples        |  155KB
// Everything else |  321KB

              
            
!
999px

Console