一个包含jquery的解决方案;Js在HTML的末尾,而同时,包含在中间的控件需要$(document).ready

a solution to include jquery & js in the end of the html while at the same time a control which is included in the middle requires $(document).ready

本文关键字:包含 document 在中间 控件 ready HTML jquery 一个 解决方案 Js      更新时间:2023-09-26

我正在使用asp.net MVC和jquery构建一个网站。
众所周知,最好的做法是在HTML页面的末尾添加javascript。
所以我基本上把jquery.js和其他js文件包含在HTML的末尾/body标签之前。
现在我有一些控件作为部分包含在页面中。他们需要在$(document).ready中添加功能。
但是我将代码写为部分中的脚本标签,然后jquery库甚至不会在那个时候被包含在内,并且我不能在部分的HTML末尾包含这个javascript。由于部分包含在html的中间,

将所有javascript文件(可能不包括jQuery文件)移动到底部。

如果你说的是好的实践,那么写内联javascript也不是一个好的实践。

所以我建议将所有的java脚本移动到单个文件,有许多工具可以合并多个javascript文件并处理它们,使用那些!!

Edit1

你可以试试:

//define this at before body (or at the beginning of body)
var arrReadyCollection = [];

内部控制器:

arrReadyCollection.push(site.module.Dialog_AcceptChanges);
arrReadyCollection.push(some_thing_Else);

在jQuery文件

之后
for (i=0;i<arrReadyCollection.length; i++)
{
     var fn= arrReadyCollection[i];
     $(document).ready(fn);
}

注意:这不是推荐的方法,这只是你解决问题的方法

你应该使用像LABjs这样的javascript加载器。

当某些库加载并运行时,可以使用它来运行javascript。

<head>
  <script src="lab.js"></script>
</head>
<body>
  <script>
    // $LAB uses async loading, no need to deferr to the end of body
    // keeping a reference to the $LAB deferred is important, so we can
    // use it from within partials (see below)
    myPage.$LAB = $LAB
      .script('someScript.js')
      .script('someOtherScript.js')
      .wait(function () {
        // your scripts are loaded!
      });
  </script>
</body>    

在你的部分中,你可以钩入LABjs,例如:

<script>
  myPage.$LAB.script('jQuery.js').wait(function () {
    // jQuery was loaded!
    // if jQuery was loaded already by another partial or your main layout
    // it will not be loaded again, but the callback will fire immediately!
  });
</script>

也就是说,你真的应该遵循Praveen给出的建议,并尽可能地将你的javascript文件捆绑起来。对服务器的每个请求都将花费时间并降低网站的响应速度。

要么修复你的"control"文件,使它们不需要内联JavaScript,要么在文件的顶部包含jQuery。

您也可以自己编写一个小的"$"函数,将包含在 jQuery之前(并且在顶部)。然而,你最好还是修复这些控件。

另一个可能的解决方案是从局部动态地添加脚本标记。但是,如果您想要运行多行代码,这可能会变得混乱,例如:

<script>
  var script = docuement.createElement('script');
  script.innerHTML = "$(document).ready(function () { doSomething(); });";
  document.body.appendChild(script);
</script>

这应该在jQuery(应该已经在正文的末尾)加载并运行之后运行。

更新:这不起作用,我假设在DOM准备好之前,在尚未准备好的DOM中插入脚本元素不会执行。

使用CDN,不要纠结于可疑的优化。来自优秀的jQuery in Action书,第1.22节

说明出于性能考虑,脚本块也可以放在最下面的文档主体,尽管现代浏览器使性能差别不大。重要的概念是避免嵌入行为结构元素中的元素。