Blog>
Snippets

Skeleton Screen UI during Data Load

Create a skeleton screen UI placeholder for content sections that are yet to be loaded to improve the perceived performance.
const skeletonMarkup = `
  <div class="skeleton-wrapper">
    <div class="skeleton-header"></div>
    <div class="skeleton-content"></div>
  </div>
`;

document.getElementById('content-placeholder').innerHTML = skeletonMarkup;
This code snippet creates a skeleton screen markup with a header and content area which is set as innerHTML of an element with the ID 'content-placeholder'.
// Add the styles for the skeleton elements
document.head.insertAdjacentHTML('beforeend', `
  <style>
    .skeleton-wrapper { background: #EEE; }
    .skeleton-header { height: 20px; background: #DDD; margin-bottom: 10px; }
    .skeleton-content { height: 150px; background: #DDD; }
    /* Add animation for skeleton loading effect */
    @keyframes loading {
      0% { background-position: -200px 0; }
      100% { background-position: calc(200px + 100%) 0; }
    }
    .skeleton-wrapper > div { background-image: linear-gradient(90deg, #EEE 25%, #DDD 50%, #EEE 75%);
                              background-size: 200px 100%;
                              animation: loading 1s infinite linear; }
  </style>
`);
This piece of code appends skeleton screen specific styles to the page. It includes the skeleton-wrapper, skeleton-header, skeleton-content styles and a loading animation to create the 'loading' effect.
function loadData() {
  // Mockup of a data load with a timeout
  setTimeout(() => {
    document.getElementById('content-placeholder').innerHTML = '<div>Content loaded</div>';
  }, 3000);
}

// Call loadData to simulate data fetching
loadData();
This function 'loadData' simulates data fetching with a timeout of 3 seconds. Once the content is 'loaded', the placeholder is replaced with actual content.