문제

Hi I'm experiencing some problems including a javascript file in my html project. When I include it like this at the end right before the body tag my site does not work correctly.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    </body>

If, however i delete the tag at the end to make it look like this

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"/>
</body>

everything works fine.

And if i include it within the head, it also works, independent of the syntax. Why does it behave like this?

도움이 되었습니까?

해결책

  1. Do what everybody else has said, regarding the <script src="..."></script>
  2. Use just src="//...", instead of src="https://..." or on non-encrypted pages (http vs https) your visitors will get security warnings for mixing the two protocols
  3. If you have written jQuery code anywhere on the page, prior to actually including the file, you're going to get reference errors, where JS will not be able to find the function ($) you're trying to use.

There is a debugger available if you use Chrome, and press CTRL+SHIFT+J : it will take you to the developer-console, where I'm sure you're going to see all kinds of reference errors.

In Firefox, it would be CTRL+SHIFT+K, in IE it's F12.

This works under the same premise as writing in other languages where you try to use libraries or other classes, but don't actually import them until the bottom of your program.

다른 팁

For browser compatibility, you must use the first form:

<script src="https://..."></script>

with an explicit closing tag </script>. If this is the case where your code is not working, then your real problem lies elsewhere and not in the way you close the tag.

There might be some race condition happening for you... it will be good if you can provide complete code... if you attach that in header ... then your jquery is successfully loades and then executes your body part... if your attaching that in body ... then closure of script is give some issues... try to play while changing your script code placements in you body tag.

</script> closing is compulsory to work in cross browsers

This might help you in ur debugging.

Why do you want to load jquery in the end of your code? If you have some other scripts that need jquery, then they should be loaded after it. So either you put all script tags in head or in the end of body — jquery should be loaded before other files that depend on it.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top