External Javascript file issue

I heard it was better to put the Javascript in an external file and call it from the html file. However, I tested some code and it does not work when it is an external file, although it does work fine when it is inline in the html file.

Here is the code:

var bigImage = document.getElementById(‘zoom’);
var smImage = document.getElementById(‘thumbnail’);

smImage.onclick = function() {

if(bigImage.style.display === “block”) {

bigImage.style.display = “none”;
}

else {
bigImage.style.display = “block”;
}

}

Any idea why it only works inline?

Most likely, the problem is that you are including your js file in a head tag or somewhere above your main content. By doing this, you are executing your js code before full html content has been attached. As a result, when your js code executes, it does not recognize any html element because there isn’t any. Try including them at the end of your html content or use onload functionality.

5 Likes

Thank you very much, it was the issue: the js file was included in the head tag!

Is there a way to add some conditions to the external script so that it is executed after the page is loaded?

1 Like

You should be able to add the js file in a script tag. The page loads first then JavaScript. You need conditionals to load an external script if the JavaScript file is in the head tag.

<html>
  <head>
  </head>
  <body>
    // your current code
    <script src="your file"></script>
  </body>
</html>

.

2 Likes

Thank you, it makes sense. But what if I cannot move the link to the js file from the head tag? Is there any way I can edit the external script itself so that it is executed AFTER the html page is loaded?

1 Like

If you use jquery you can use .ready().

$(document).ready()

The issue with vanilla JavaScript is compatibility issues across browsers. Here is a stack overflow article with vanilla JavaScript code that works similar to jQuery function. Look at the first response in the article.
Last option if you don’t care if it works in all browsers is DomContentLoaded. Look at the “Browser compatibility” sub-heading to see which browsers are compatible. There is example code under the “Example” sub-heading. You will need to place all your code inside the the callback.

1 Like

I’m not op but I was having the same issue for like three nights and your answer finally fixed it. Thank you so much.

1 Like

You can put the script tag at the head with async like this:
<script src="your-script.js" async>

1 Like

Thanks! you saved my day

1 Like