I am trying to add an image to a website using Javascript. I am doing this using createElement, and setAttribute to point to the image in my file directory. Here is the very basic code:
var lambda = document.createElement("img");
lambda.setAttribute("src", "img/512.png");
var body = document.querySelector("body");
body.prepend(lambda);
I am confused because when the website loads, the image does not render properly. However, when I inspect the broken image and copy/paste the html from my browser into my html document and then reload, the image loads properly. My question is, why is the browser unable to load the image when I call it using Javascript, but it works perfectly when the code generated by Javascript is copied into the html document?
Try this to see what is going on, and then look in the network tab to see what is loaded
const imgSrc = "img/512.png"; // "https://cdn.iconscout.com/icon/premium/png-512-thumb/lambda-2-550999.png";
const lambda = document.createElement("img");
lambda.onload = function() {document.querySelector("body").prepend(lambda)}
lambda.onerror = function(err) { console.log(err,err.path) }
lambda.setAttribute("src",imgSrc);
For example for your image URL I get this in the network console
Request URL: https://stacksnippets.net/img/512.png
Request Method: GET
Status Code: 404 Not Found
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With