javascriptimagebroken-image

Getting broken image but it loads as a new tab


I have the following little script that seems to work but two of the images appear broken. They load when I right click and load as new tab:

var target = document.getElementById('target');
    var counter = 0;
    var myPictures = [        
        'https://media.giphy.com/media/3ohhwJax6g4Y8BK30k/giphy.gif',
        'https://media.giphy.com/media/3o7aD5tv1ogNBtDhDi/giphy.gif',
        'https://media.giphy.com/media/1nkUav308CBws/giphy.gif'
    ];

    function nextPic() {
      counter += 1;
      if (counter > myPictures.length -1) {
        counter = 0;
      }
      target.src = myPictures[counter];
    }
<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <img id="target" src="https://media.giphy.com/media/1nkUav308CBws/giphy.gif" width="107" height="98" />
  <input type="button" onclick="nextPic()" value="change image" />



    
 
</body>
</html>


Solution

  • Just move this line inside your nextPic() function so you don't try to grab that div before it gets loaded in the DOM.

    function nextPic() {
      var target = document.getElementById('target');
      ...
    

    Sometimes <script defer> will automagically wait for the DOM to load, sometimes it doesn't. It's JavaScript. It is what it is.

    defer

    This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded. This attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect. To achieve a similar effect for dynamically inserted scripts use async=false instead.

    Here's a good backstory on script loading.