Using a gif animation, we can use CSS to insert a loading animation while iframe is being loaded. Animation will be a gif like background
of a class we will use in the div
that will contain the iframe
, let’s call this class iframe-div
. See the CSS:
.iframe-div {
text-align: center;
background: url(https://media1.giphy.com/media/3oEjI6SIIHBdRxXI40/200.gif)
center center no-repeat;
}
Now in Javascript, let’s create an iframe using var iframe = document.createElement('iframe');
, like you did for the div
. I’ll put code with explanations:
function texton(x) {
var a = document.createElement('div');
var iframe = document.createElement('iframe'); // criamos um iframe dessa forma
a.className = 'iframe-div'; // essa classe importante para a animacao
// atribuir propriedades do iframe
iframe.setAttribute('src', x); // source recebido como parametro
iframe.setAttribute('id', 'iframe'); // esse id vai ser importante
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('width', '500');
iframe.setAttribute('height', '340');
a.appendChild(iframe); // adicionamos o ifram dentro da div
a.innerHTML +=
'<button onclick="textoff()" class="btn btn-green" id="bclose">Fechar</button>';
document.body.appendChild(a);
var ifr = document.getElementById('iframe'); // aqui vamos pegar o elemento iframe
// pelo id para ai sim verificarmos se o iframe carregou ou nao
// agora sim podemos verificar se o iframe carregou.
ifr.onload = function () {
console.log('carregado com sucesso');
a.setAttribute('class',''); removemos a classe para a animacao ser removida da div
};
}
texton('https://www.youtube.com/embed/O6P86uwfdR0');
See the example below:
Note: the OS will not carry the content of iframe
, but serves to exemplify
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style>
.iframe-div {
text-align: center;
background: url(https://media1.giphy.com/media/3oEjI6SIIHBdRxXI40/200.gif)
center center no-repeat;
}
</style>
<body>
<script>
function texton(x) {
var a = document.createElement('div');
var iframe = document.createElement('iframe');
a.className = 'iframe-div';
iframe.setAttribute('src', x);
iframe.setAttribute('id', 'iframe');
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('width', '500');
iframe.setAttribute('height', '340');
a.appendChild(iframe);
a.innerHTML +=
'<button onclick="textoff()" class="btn btn-green" id="bclose">Fechar</button>';
document.body.appendChild(a);
var ifr = document.getElementById('iframe');
ifr.onload = function () {
console.log('carregado com sucesso');
};
}
texton('https://www.youtube.com/embed/O6P86uwfdR0'); // criando um iframe dinamicamente
</script>
</body>
</html>
This possible solution solves your problem?
There is an approach using only CSS. You tried to use otherwise or it has to be via JS itself?
– Cmte Cardeal