[英]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"); ?>
我对此有两个担忧:
有人可以让我知道这是正确的还是我应该在此处进行任何更改?
非常感谢您对此提供的任何帮助。
$(document).ready
的函数可以解决此问题。 来自document.ready上的JQuery文档 。 在文档“就绪”之前,无法安全地操纵页面。 jQuery为您检测到这种就绪状态。 $(document).ready()内包含的代码仅在页面Document Object Model(DOM)准备好执行JavaScript代码后才能运行。
仅在加载jQuery之后,即在页脚文件中的jQuery <script>
标记之后,才应加载$(document).ready(...)
东西,如下所示:
<script src="includes/js/jQuery.min.js"></script>
<script src="includes/js/nameOfExternalJsFile.js"></script>
最好将所有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 */ });
您可以在页面底部将footer.php的内容更改为手动包含/nameOfExternalJsFile.js。 这是最安全的方法,因为您可以在加载其他脚本之前先加载jquery。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.