admin管理员组

文章数量:1325767

I'm trying to load an element only after the img element has been loaded, but I've tried everything I can think of and nothing is working. Right now I'm trying to see where the code stops working and I found that the alert I set up isn't running after the line I need the code to execute from.

$img = $('#picture');
function bubbleOnLoad() {
  $(document).ready(function() {
    $img.load(function(){
    alert('document loaded')
    $('#left-bubble').show();
  })
})

The $img is defined within a function. The alert works at the document.ready line but not after the $img.load. I have tried to add eventlisteners, jquery .on, .load, and a bunch of others. I'm also calling the function to run within my init function. Can someone explain to me why nothing is working?

function choosePic() 
 $('.speechbubble').hide();
 $('#picture').remove();
 var randomNum = Math.floor(Math.random() * samplePics.length);
 var img = new Image();
 img.onload = function() {
  $('.playing-field').prepend(img);
 handleImageLoad();
 }
 img.src = samplePics[randomNum];
 img.id = "picture";
}


var samplePics = 
 "assets/images/barack-obama.jpg",
 "assets/images/donald-trump_3.jpg",
 "assets/images/dt-2.jpg",
 "assets/images/bill-clinton.jpg",
 "assets/images/Rose-Byrne.jpg",
 "assets/images/pic.jpeg", 
 "assets/images/priest.jpg", 
 "assets/images/tb.jpg",
 "assets/images/test.jpg", 
 "assets/images/amy-poehler.jpg",
 "assets/images/stephen-colbert.jpg",
 "assets/images/aziz-ansari.jpg"
];

I'm trying to load an element only after the img element has been loaded, but I've tried everything I can think of and nothing is working. Right now I'm trying to see where the code stops working and I found that the alert I set up isn't running after the line I need the code to execute from.

$img = $('#picture');
function bubbleOnLoad() {
  $(document).ready(function() {
    $img.load(function(){
    alert('document loaded')
    $('#left-bubble').show();
  })
})

The $img is defined within a function. The alert works at the document.ready line but not after the $img.load. I have tried to add eventlisteners, jquery .on, .load, and a bunch of others. I'm also calling the function to run within my init function. Can someone explain to me why nothing is working?

function choosePic() 
 $('.speechbubble').hide();
 $('#picture').remove();
 var randomNum = Math.floor(Math.random() * samplePics.length);
 var img = new Image();
 img.onload = function() {
  $('.playing-field').prepend(img);
 handleImageLoad();
 }
 img.src = samplePics[randomNum];
 img.id = "picture";
}


var samplePics = 
 "assets/images/barack-obama.jpg",
 "assets/images/donald-trump_3.jpg",
 "assets/images/dt-2.jpg",
 "assets/images/bill-clinton.jpg",
 "assets/images/Rose-Byrne.jpg",
 "assets/images/pic.jpeg", 
 "assets/images/priest.jpg", 
 "assets/images/tb.jpg",
 "assets/images/test.jpg", 
 "assets/images/amy-poehler.jpg",
 "assets/images/stephen-colbert.jpg",
 "assets/images/aziz-ansari.jpg"
];
Share Improve this question edited Aug 4, 2015 at 21:39 Tiffany Haltom asked Aug 4, 2015 at 20:46 Tiffany HaltomTiffany Haltom 1597 bronze badges 9
  • 1 is the img being loaded dynamically via JavaScript? Or with an img html tag? – Jonathan.Brink Commented Aug 4, 2015 at 20:50
  • 1 did you read the docs, especially "Caveats of the load event when used with images" api.jquery./load-event – Pevara Commented Aug 4, 2015 at 20:51
  • 2 why are you wrapping it in the bubbleOnLoad function? is that function ever called? – trex005 Commented Aug 4, 2015 at 20:52
  • 1 Why is there a $(document).ready(function() inside of function bubbleOnLoad? That seems very odd to me... – nurdyguy Commented Aug 4, 2015 at 20:57
  • 1 The braces are unbalanced, which probably isn't helping. – Richard Poole Commented Aug 4, 2015 at 20:57
 |  Show 4 more ments

4 Answers 4

Reset to default 4

You had some syntax errors in your code which I corrected and came up with this:

function bubbleOnLoad() {
    $img = $('#picture');
    $img.load(function () {
        alert('document loaded');
        $('#left-bubble').show();
    });
}

$(document).ready(function () {
    bubbleOnLoad();
});

Here is the JSFiddle demo

In you code you are not even telling the browser it's supposed to run a code after image load. you should do something like this:

$(function(){

  // DOM Content is ready, let's interact with it.

  $('#picture').attr('src', 'image.jpg').load(function() {  
    // run code
    alert('Image Loaded');  
  });

});

Also according to docs a mon challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have pletely loaded. There are several known caveats with this that should be noted. These are:

  • It doesn't work consistently nor reliably cross-browser
  • It doesn't fire correctly in WebKit if the image src is set to the same src as before
  • It doesn't correctly bubble up the DOM tree Can cease to fire for images that already live in the browser's cache

Try this jQuery plugin waitForImages

https://github./alexanderdickson/waitForImages

//Javascript/jQuery
$(document).ready(function(){
  var counter = 0,totalImages= $('#preloader').find('img').length; 
  $('#preloader').find('img').waitForImages(function() {
    //fires for all images waiting for the last one.
    if (++counter == totalImages) {
      $('#preloader').hide();
      yourCallBack();
    }
  });
});
/*css*/
#preloader{
  position:absolute;
  top:-100px;/*dont put in DOM*/
}

#preloader > img{
  width:1px;
  height:1px;
}
<!--HTML [add the plugin after jQuery] -->
<script src="http://cdnjs.cloudflare./ajax/libs/jquery.waitforimages/1.5.0/jquery.waitforimages.min.js" ></script>
 

<!--HTML [after body start] -->
<div id=preloader>
  <img src="1.jpg" />
  <img src="2.jpg" />
  <img src="3.png" />
  <img src="4.gif" />
  <img src="5.jpg" />
</div>

You can only access the HTML element after it was created in DOM.
Also you need to check if the image was loaded before showing.
Thus your code need to look something as below:

$(document).ready(function() {
    bubbleOnLoad(); 
});
      
function bubbleOnLoad() {
    var newSrc = "https://lh5.googleusercontent./-lFNPp0DRjgY/AAAAAAAAAAI/AAAAAAAAAD8/Fi3WUhXGOY0/photo.jpg?sz=328";
    $img = $('#picture');
    $img.attr('src', newSrc) //Set the source so it begins fetching
      .each(function() {
          if(this.plete) {
            alert('image loaded')
            $('#left-bubble').show();
          }
      });
 }
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="left-bubble" style="display:none">
  <img id="picture"/>
</div>

本文标签: javascriptHow to run code after an image has been loaded using JQueryStack Overflow