HTML / jQuery: 如何正确包含外部 jQuery 文件

HTML / jQuery: How to properly include external jQuery file

我是 JS 和编程的新手,希望有人能帮助我。

我目前正在构建一个网站,其中每个页面都有其单独的 HTML / PHP 文件。 jQuery 和我的全局/通用 JS 函数通过单独的包含文件“footer.php”包含在所有这些页面的页脚中。

到目前为止一切正常。

现在我有一些页面会使用特定的jQuery函数,所以我想只有在加载这样的页面时才加载相应的JS。

为此,我将相应的代码保存在单独的 JS 文件中(例如 nameOfExternalJsFile.js),然后 将其中的所有内容包装在以下内容中:

$(document).ready(function(){
   // ...
}); 

然后我对相应的 PHP 页面(示例)进行了以下更新:

<head>
    <?php 
        require_once("includes/header.php");
    ?>

    <!-- here I want to include the specific jQuery functions -->
    <script src="includes/js/nameOfExternalJsFile.js"></script>
</head>
<!-- ... -->
<!-- here I include the main JS functions -->
<?php require_once("includes/footer.php"); ?>

我对此有两个顾虑:

  1. 我不确定这是否是包含此类文件的正确方法,因为 我需要准备好它们的文档。
  2. 我在页脚中包含了我的主要 JS,因为有人告诉我这会有所改进 性能,但我可以在 header 中包含 jQuery 函数吗?

有人可以告诉我这是否正确,或者我是否应该在这里更改任何内容?

非常感谢您对此提供的任何帮助。

你应该只在加载 jQuery 之后加载 $(document).ready(...) 东西,也就是说,在页脚文件中,在 jQuery <script> 标记之后,像这样:

<script src="includes/js/jQuery.min.js"></script>
<script src="includes/js/nameOfExternalJsFile.js"></script>

您可以更改 footer.php 的内容以在页面底部手动包含 /nameOfExternalJsFile.js。这是最安全的方法,因为您可以在加载其他脚本之前加载 jquery。

最好将所有 JS 文件放在正文末尾

<html>
<head></head>
<body>
... Some HTML
<script>SomeScripts</script>
</body>
</html>
</pre>

If you want to be sure that your external scripts are loaded after page load use: $(function(){ /* Your code from the scripts */ });

  1. 将函数包装在 $(document).ready 中会自动解决这个问题。来自 JQuery documentation on document.ready.

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

  1. 从技术上讲,将脚本包含在页眉还是页脚中并不重要,只要先加载 JQuery 然后再加载脚本即可。

    也就是说,通常建议两个脚本都放在结束正文标记之前,以按照您的建议提高性能。有一些文章讨论了这个问题,例如来自 Yahoo! 的 this post from performance expert Steve Souders and this guide。出色的表现团队。