Load Iframe only when clicking

1

I have a website and I need to create a menu that by clicking on a button opens an html inside the html but I need to load it just by clicking it because it is very heavy for more images and if it loads everything would cost a lot of data to the clients that the majority connects with mobile data so I want that only if the client clicks the data is downloaded .. I have everything right I just need some code so that the iframe does not load until it clicks Does anyone have any code that can be used?

    
asked by Alst Adm 29.10.2018 в 04:16
source

3 answers

1

In your HTML you declare the iframe tag without the src attribute

<iframe style='display:none' id='frame' width='400' height='400' frameborder='0'></iframe>

We import jQuery

<script src='https://code.jquery.com/jquery-1.12.4.min.js'></script>

Then in javascript we make a function to load the url you want.

 function loadPage(){
     var frame = $('#frame');
     var url = 'AQUI LA URL QUE QUIERAS INSERTAR EN TU IFRAME';
     frame.attr('src',url).show();
 }

and finally call the function from any node that you want for example a <button onclick='loadPage()'>Abrir iframe</button>

    
answered by 29.10.2018 / 11:58
source
0

You can do it in two ways:

1) Creating the iframe when you click on the menu:

document.getElementById("crear").addEventListener("click", () => {
    
  var iframe = document.createElement('iframe');
  var html = '<body>Tu nuevo HTML</body>';
  iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
  document.getElementById("contenido").appendChild(iframe);
    
}); 
<button id="crear">Menu Crear Iframe</button>
<div id="contenido"></div>

2) The iframe already exists and you only set the src attribute when you click on the menu:

document.getElementById("crear").addEventListener("click", () => {
    
  var html = '<body>Tu nuevo HTML</body>';
  document.getElementById("iframe").src = 'data:text/html;charset=utf-8,' + encodeURI(html);
    
});
<button id="crear">Menu Crear Iframe</button>
<div id="contenido">
  <iframe id="iframe"></iframe>
</div>

I hope you find it useful

    
answered by 29.10.2018 в 15:44
-1

Maybe this function will help you:

function show() {
   let iframe = document.createElement('iframe');
   let att1 = document.createAttribute('src');
   att1.value = '<src del iframe que vas a colocar>';
   // aquí puedes añadir los atributos que quieras
   let div = document.querySelector('#div');
   div.appendChild(iframe);
}
    
answered by 29.10.2018 в 04:37