Parro
Parro

Reputation: 27

To Load a video embed using "onclick" function to optimize a web page

First of all, sorry for my bad English. I would like to upload a video embed to a web page when I click a button. I would like to do this because facebook embed videos are heavy and if they load them all the page there is about 3/4 seconds to load. I'm trying to do it with Jquery but I do not know what to use. At this moment I'm trying with the "load" function ...

This is a very simple example:

<button id="btn_id" class="btn btn-default" type="submit">Button</button>

<div class="embed-responsive embed-responsive-16by9" id="ld_video">    
<div>

<script>
  btn_id.onclick = function(){
  $("#ld_vid").load(<iframe src=".........);
  };
</script>

Upvotes: 0

Views: 3996

Answers (1)

Andrew L
Andrew L

Reputation: 5486

All you need is a button that when clicked- dynamically changes the src attribute of the iframe. This will load a video when the user clicks the button instead of all the videos load when the user accesses the website. Here is a minimal example of how to achieve this.

document.getElementById("myButton").onclick = function() {
  var iframe = document.getElementById("myIframe");
  iframe.src = "https://www.youtube.com/embed/6wUxpFu9Wvo";
  iframe.style.display = "";
}
<iframe id="myIframe" width="560" height="315" style="display:none;" src="" frameborder="0" allowfullscreen></iframe>
<button id="myButton">Load video</button>

Or using jQuery

$(document).ready(function() {
  $("#myButton").on("click", function() {
    var $iframe = $("#myIframe");
    $iframe.attr("src", "https://www.youtube.com/embed/6wUxpFu9Wvo");
    $iframe.show();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<iframe id="myIframe" width="560" height="315" style="display:none;" src="" frameborder="0" allowfullscreen></iframe>
<button id="myButton">Load video</button>

Upvotes: 5

Related Questions