我对 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"); ?>
我对此有两个担忧:
- 我不确定这是否是包含此类文件的正确方法,因为 我需要将它们准备好文件。
- 我在页脚中包含了我的主要 JS,因为我被告知这会改进 性能,但是我可以在 header 中包含 jQuery 函数吗?
有人可以告诉我这是否正确或者我是否应该在这里更改任何内容?
非常感谢您对此提供的任何帮助。
最佳答案
- 将函数包装在
$(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.
从技术上讲,无论将脚本包含在页眉还是页脚中都没有关系,只要先加载 JQuery,然后再加载脚本即可。
也就是说,通常建议这两个脚本都放在结束正文标记之前,以按照您的建议提高性能。有一些文章讨论了这个问题,例如 this post来自性能专家 Steve Souders 和 this guide来自雅虎!卓越的绩效团队。
关于javascript - HTML/jQuery : How to properly include external jQuery file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31120916/