0

I have a div with text in it and a background image. When I load the page the text always appear 1st(assume i have low speed internet connection). How can i make the background image load before text? Can You please give me solution in both jquery and javascript

dramasea
  • 3,370
  • 16
  • 49
  • 77
  • Can this help? http://stackoverflow.com/questions/476679/preloading-images-with-jquery – Yoav Kadosh Dec 17 '12 at 16:41
  • I don't really understand I was going to suggest chucking java at the bottom – TheBlackBenzKid Dec 17 '12 at 16:43
  • For those answers suggesting the jQuery Load event, be sure to see the "caveats" section in the API: http://api.jquery.com/load-event/. As such, I'd probably suggest user1026361's answer, if you are ok w/ preloading the image. – Grinn Dec 17 '12 at 16:50

4 Answers4

3

Add the text in the onload event handler for the image.

Note: If you want to keep using a div tag with a background image rather than an img tag, you'll have to add the text during the window.onload event (see this answer for the details).

Emil Sierżęga
  • 1,785
  • 2
  • 31
  • 38
Briguy37
  • 8,342
  • 3
  • 33
  • 53
2

Assuming your div looks like this:

<div id="Derp" style="CSS-for-background-image-here">Magical ponies!</div>

I would try removing the text completely and then add this kind of jquery call:

<script>
    $(document).ready(function() {
        $('#Derp').load(function() {
            $('#Derp').text("Magical ponies!");
        });
    });
</script>

The $('#Derp').load(...) is the key here. See the docs for load(). It has an example of exactly what you need.

Joel Peltonen
  • 13,025
  • 6
  • 64
  • 100
1

you could populate the content onload.

Start with this:

<div id="content"></div>

Then, in jquery, do this:

 $(document).ready(function() {
    mybg= new Image(); 
    mybg.onload=function(){
      $('#content').html('YOURTEXTHERE');
    }
    mybg.src = "PATH/TO/IMG";
    });
user1026361
  • 3,627
  • 3
  • 22
  • 20
0

your simple answer is .load you can do when your window gets loaded fully and then text appears:

$(function(){
    $(window).load(function() {
        $('p').fadeIn(800);
    });​
});

what this is doing is fading in the p tag with text when whole window gets loaded.

you can find a demo here: http://jsfiddle.net/a5P8b/

Jai
  • 74,255
  • 12
  • 74
  • 103