skip to Main Content

I am using JavaScript to load dynamic PDF content into an <embed> element:

document.querySelector('button').addEventListener("click", (event) => {
  document.querySelector('embed').src = 'https://example.com/';
});
<div id="embed-container">
  <embed>
</div>
<button>Load Embed Content</button>

How can I detect when it finished loading? You can see in the devtools that when the button is clicked, there’s a pending GET request to that URL. In my case it takes a few seconds to load so I want to display a loading animation and once it finished pending and I get 200 then show the <embed> (Instead of displaying a blank page for a few seconds)

2

Answers


  1. You can hide the element with display: none and use the load event to make it visible once the content has been loaded.

    const emb = document.querySelector('embed');
    const btn = document.querySelector('button');
    
    btn.addEventListener("click", () =>  emb.src = 'https://example.com/');
    emb.addEventListener('load', () => emb.style.display = 'block');
    embed {display: "none";}
    <div id="embed-container">
      <embed>
    </div>
    <button>Load Embed Content</button>
    Login or Signup to reply.
  2. You can create a load event for the embed during the button click and add a loader too:

    let embedContainer = document.querySelector("#embed-container");
    document.querySelector('button').addEventListener("click", (event) => {
      embedContainer.classList.add("loading");
      let embed = embedContainer.querySelector('embed');
      embed.src = 'https://example.com/';
      embed.addEventListener("load", function() {
          embedContainer.classList.remove("loading");
          embedContainer.classList.add("loaded");
      });
    });
    #embed-container > embed {
        display: none;
    }
    
    #embed-container > .placeholder {
        display: none;
    }
    
    #embed-container.loading > .placeholder {
        display: block;
        width: 302px;
        height: 152px;
        border: 1px solid black;
    }
    
    .placeholder img {
        width: 100%;
        height: 100%;
    }
    
    #embed-container.loaded > .placeholder {
        display: none;
    }
    
    #embed-container.loaded > embed {
        display: block;
    }
    <div id="embed-container">
      <embed>
      <div class="placeholder">
          <img src="https://upload.wikimedia.org/wikipedia/commons/b/b1/Loading_icon.gif">
      </div>
    </div>
    <button>Load Embed Content</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search