External Javascript file issue

External Javascript file issue
0.0 0

#1

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?


#2

Can you post a link to the html file that references the JavaScript file and a link to the JavaScript file itself? It could help us to understand where the problem is.


#3

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.


#4

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?


#5

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>

.


#6

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?


#7

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.