1

I'm new in javascript and php.

My body page has a link of a background image. I have a div (div.loader) and in my js code, I have a variable var countdown = 15.When my countdown is 0, it will add a class loaded to my div but I don't know how long the image will load and also the images load so slow (for me). So I want to call a function that will add a class loaded if the image loaded completely. (here's the link of my website loader: acromix.net16.net)

How do I call a function after the background image loads using javascript or php? (no extensions or plugins)

(This might be a duplicate but this link (jquery,plugins) is not answering my question)

Community
  • 1
  • 1
newbieguy
  • 658
  • 2
  • 11
  • 29

3 Answers3

1

You can do something like this in pure javasciprt.

var backgroundImageUrl = "backgorundImageName.jpg";

// checking if image is already there in cache 
if (sessionStorage.getItem(backgroundImageUrl)) {
  document.body.style.backgroundImage = "url('" + backgroundImageUrl + "')";
} else {
  var img = new Image();
  img.src = backgroundImageUrl;
  img.onload = function() {
    document.body.style.backgroundImage = "url('" + backgroundImageUrl + "')";
    sessionStorage.setItem(backgroundImageUrl, true);
    img = undefined;
  };

}

I have used sessionStorage to track if the image is already in the cache or not. onload won't fire if image is already present in the cache.

jad-panda
  • 2,509
  • 16
  • 22
0

If you are talking about javascript then you can use the onload() event function in the body tag of html.

Javascript method:

<script>
function callFunc()
{
  //call your another function here
}
</script>

<body onload="callFunc()">

</body>

And if you are thinking to use jquery then call that function in

$(function(){
  //your function to be called
})

I hope this helps you.

Sourabh Kumar Sharma
  • 2,864
  • 3
  • 25
  • 33
0

Have you tried attaching eventListener or onload event to your image object and then perform whatever you are trying to do?

object.addEventListener("load", myScript);

OR

object.onload=function(){myScript};

You should create image objects in javascript and define their src. and then use the event to do whatever you are trying to do .

Here is one example

var imageName = new Image();
imageName.src = "imageName.jpg";
imageName.onload = function()
{
//do your work here
};
dark knight
  • 85
  • 1
  • 11