2

When i add this:

<script src="script.js"></script>
<script src="jquery-3.5.1.min.js"></script> 

to my index.html file in the head of the file, and i create a JavaScript file, it looks like the html doesn't recognize it.

But when i add this:

<script type="text/javascript">
    //code
</script>

to my index.html file in the body of the file, all of the code i done in JavaScript works.

Can somebody explain why this happens?

2
  • add your external js files at the bottom of the body instead of the head Commented Jan 6, 2021 at 23:30
  • 1
    script.js needs to come after jquery. Commented Jan 6, 2021 at 23:33

2 Answers 2

1

It’s always a good practice to add jQuery code just before the closing </body> tag. If you have not done that, then use the defer attribute.

Also if you’re writing jQuery code make sure that your code is placed after the jQuery link code.

Sign up to request clarification or add additional context in comments.

Comments

1

Don't add your JS files in the head. You are most likely going to be accessing DOM elements, and those elements are defined in the HTML. If you insert a script above the html, the elements won't be recognized because they're not defined yet. Add all of your scripts after the body, I add mine after the closing html just to be safe. And please add your script after your jQuery script.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.