I have the following HTML template:
<template id="type1">
<div class='type1'>
<a>
<div class='poster'></div>
<div class='content'>
<div class='title'></div>
<div class='description'></div>
</div>
</a>
</div>
</template>
I’m calling for some API and receive a list of objects with this structure:
[{
id: 'someid',
poster: 'some_image_url',
url: 'some_link_url',
title: 'Title',
description: 'description'
}, {...}]
I run in loop on all objects and for each create a clone of the template:
const sonstruct = data => {
const template = document.querySelector('#type1')
const clone = template.content.cloneNode(true)
clone.querySelector('a').setAttribute('href', data.url)
clone.querySelector('.poster').setAttribute('style', `background-image: url("${data.poster}")`)
clone.querySelector('.title').textContent = data.title
clone.querySelector('.description').textContent = data.description
return clone
}
So far everything works just fine. The problem begins when I decide to check if the image in the poster
link is loaded, and if not – set some default image. First I tried to do the following (instead of clone.querySelector('.poster')
):
const img = new Image
img.onload = function() {
clone.querySelector('.poster').setAttribute('style', `background-image: url("${data.poster}")`)
}
img.onerror = function() {
clone.querySelector('.poster').setAttribute('style', 'background-image: url("./assets/default.png")')
}
img.src = data.poster
And I received the following error: clone.querySelector(...) is null
I tried to use closures:
img.onload = (function (clone) {
return function () {
clone.querySelector('.poster').setAttribute('style', `background-image: url("${data.poster}")`)
}
})(clone)
img.onerror = (function (clone) {
return function () {
clone.querySelector('.poster').setAttribute('style', 'background-image: url("./assets/default.png")')
}
})(clone)
Alas, same result, same error.
I also tried to use .apply(clone)
on the methods above, however in that case all the images were set to default image in the onerror
method, even though the URL in data.poster
did return an image.
Why is this happening and how to make it work?