Lynne
Lynne

Reputation: 547

jQuery doesn't work in an external js file

I'm a beginner of jQuery. I wanne write my jQuery in an external js file instead of in the head of html file, but it failed.

index.html:

<!DOCTYPE html>
<head>
<script src="js/func.js"></script>
</head>
<body>
<p id="response">response is shown here</p>
<button id="bt_testJQ">jq test</button>
</body>
</html>

func.js

document.write("<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>")`
`$(document).ready(function () {
    $("#bt_testJQ").click(function () {
        $("#response").toggle();
    })
})

`

Upvotes: 0

Views: 4581

Answers (2)

Quentin
Quentin

Reputation: 943150

This has nothing to do with putting the code in an external file, you'd have the same problem if it was inline.

document.write's output is placed after the <script></script> element and parsed by the HTML parser when the script has finished running. Effectively, you are:

  1. setting up jQuery to load
  2. Trying to use jQuery
  3. actually loading jQuery

You can't use jQuery before you load it.

The simple solution to this is to use two script elements in the HTML and load jQuery first.

<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>
<script src="js/func.js"></script><!-- with the document.write line removed -->

just wanna to avoid importing the jquery in every html file.

This is best handled by either:

  • Using a template system.
  • Using a build system that combines the contents of all your scripts, including third party libraries, into a single file.

Upvotes: 2

Dren
Dren

Reputation: 319

A better way of doing this is have the jquery library called at the head and have your external js script at the last part of the body of your html

html code

<!DOCTYPE html>
<head>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>
</head>
<body>
<p id="response">response is shown here</p>
<button id="bt_testJQ">jq test</button>
<script src="js/func.js"></script>
</body>
</html>

Upvotes: 0

Related Questions