Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save leenyburger/bf6d467ab2a47c2973d932b1424315bb to your computer and use it in GitHub Desktop.

Select an option

Save leenyburger/bf6d467ab2a47c2973d932b1424315bb to your computer and use it in GitHub Desktop.
How to add a loading spinner to Simple File Upload while waiting for uploader

If you're seeing a slow load on the iframe, you can move your script to defer or async and (if desired) add a loading gif.

Here's the code:

CSS

/* Spinner Styles */
.spinner {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 24px;
  height: 24px;
}

.spinner::after {
  content: '';
  display: block;
  width: 24px;
  height: 24px;
  border: 3px solid rgba(0, 0, 0, 0.3);
  border-radius: 50%;
  border-top-color: #000;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.hidden {
  display: none;
}

#iframe-container {
  position: relative;
  display: inline-block; /* Ensure it does not take full width */
}

#iframe-container iframe {
  display: block;
}

Javascript

Add a mutation observer to listen for the uploader load

<script>

document.addEventListener("DOMContentLoaded", function() {
  const inputTag = document.querySelector('.simple-file-upload');
  const spinner = document.getElementById('spinner');
  const iframeContainer = document.getElementById('iframe-container');

  // Function to hide the spinner once the iframe is loaded
  function hideSpinner() {
    spinner.classList.add('hidden');
  }

  // Monitor for changes in the DOM to detect when the iframe is added
  const observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      mutation.addedNodes.forEach(function(node) {
        // Check if the added node is the specific iframe related to the uploader
        if (node.tagName === 'IFRAME' && node.classList.contains('widgetFrame')) {
          node.onload = hideSpinner;
        }
      });
    });
  });

  observer.observe(iframeContainer, { childList: true });

  // In case the iframe is already loaded before we start observing
  const existingIframe = document.querySelector('iframe.widgetFrame');
  if (existingIframe) {
    existingIframe.onload = hideSpinner;
  }
});
</script>

HTML

<div id="iframe-container">
  <!-- Your uploader below, this is just an example -->
  <input id="uploader-preview-here-4190" class="simple-file-upload spinner" type="hidden" data-maxFileSize="5" data-accepted="image/*">
  <div id="spinner" class="spinner"></div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment