Como verificar a imagem de fundo (CSS) foi carregada?
-
20-09-2019 - |
Pergunta
Eu tenho a seguinte classe CSS
.bg {
background-image: url('bg.jpg');
display: none;
}
que estou aplicando uma tag TD.
Minha pergunta é como posso dizer com JavaScript/jQuery que a imagem de fundo acabou com o carregamento?
Obrigada.
ATUALIZAÇÃO: Propriedade de exibição adicionada. Desde o meu principal objetivo, ele o altere à vista.
Solução
A única maneira de conhecer isso é carregar a imagem usando JavaScript e, em seguida, definir essa imagem como o backgroud.
Por exemplo:
var bgImg = new Image();
bgImg.onload = function(){
myDiv.style.backgroundImage = 'url(' + bgImg.src + ')';
};
bgImg.src = imageLocation;
Outras dicas
Dê a classe a uma div com visibility:hidden
Na página inicial do carregamento. Dessa forma, ele já estará no cache do navegador quando você atribui a classe à sua célula de tabela.
@Jamie Dixon - Ele não disse que queria fazer qualquer coisa com a imagem de fundo, apenas saiba quando está carregada ...
$(function( )
{
var a = new Image;
a.onload = function( ){ /* do whatever */ };
a.src = $( 'body' ).css( 'background-image' );
});
Este artigo pode ajudá -lo. Seção relevante:
// Once the document is loaded, check to see if the
// image has loaded.
$(
function(){
var jImg = $( "img:first" );
// Alert the image "complete" flag using the
// attr() method as well as the DOM property.
alert(
"attr(): " +
jImg.attr( "complete" ) + "\n\n" +
".complete: " +
jImg[ 0 ].complete + "\n\n" +
"getAttribute(): " +
jImg[ 0 ].getAttribute( "complete" )
);
}
);
Basicamente, selecione a imagem em segundo plano e faça a verificação para ver que está carregada.
Você também pode fornecer uma função que simplesmente substitui a tag IMG pela div/background para que você se beneficie do atributo Onload e da flexibilidade da div.
Obviamente, você pode ajustar o código para melhor se adequar à sua necessidade, mas, no meu caso, também garanto que a largura ou a altura seja preservada para um melhor controle do que espero.
Meu código da seguinte maneira:
<img src="imageToLoad.jpg" onload="imageLoadedTurnItAsDivBackground($(this), true, '')">
<style>
.img-to-div {
background-size: contain;
}
</style>
<script>
// Background Image Loaded
function imageLoadedTurnItAsDivBackground(tag, preserveHeight, appendHtml) {
// Make sure parameters are all ok
if (!tag || !tag.length) return;
const w = tag.width();
const h = tag.height();
if (!w || !h) return;
// Preserve height or width in addition to the image ratio
if (preserveHeight) {
const r = h/w;
tag.css('width', w * r);
}
else {
const r = w/h;
tag.css('height', h * r);
}
const src = tag.attr('src');
// Make the img disappear (one could animate stuff)
tag.css('display', 'none');
// Add the div, potentially adding extra HTML inside the div
tag.after(`
<div class="img-to-div" style="background-image: url(${src}); width: ${w}px; height:${h}px">${appendHtml}</div>
`);
// Finally remove the original img, turned useless now
tag.remove();
}
</script>