[英]How to add a row in a jquery datatable with custom html for each column keeping html code in template and javascript code in separate files?
[英]Keeping my jQuery code away from the html files
我正在学习jQuery并创建了几个插件。 不幸的是,由于我公司的编码实践,他们希望将所有javascript代码提取到js文件。 这对我来说有两个挑战:
任何建议,更正都非常感谢
谢谢
1.
绝对。
只需在html中添加一个脚本引用,如下所示:
<script type='text/javascript' src='js/yourfile.js'></script>
然后用。启动你的.js文件
jQuery(function() {
foo;
...
bar;
});
或任何其他快捷方式启动jQuery代码块。
2.
您应该通过Minify之类的操作运行脚本,然后再将其发送给用户。 这将合并文件并很好地打包它们,这样它们占用的空间更少。
在外部javascript文件中使用$(document).ready()很好 - 它将完全相同:)事实上 - 它不仅会起作用,而且它是一个很好的做法,因为它有助于分离内容(HTML)行为(Javascript)。
在回答您的部分问题时 - 您可以将所有插件合并到一个javascript文件中,并链接到<head>中的那个。 你也可以尝试缩小脚本,虽然这通常有点矫枉过正,直到网站上线。
当我使用jQuery时,我通常使用这种结构:
<html>
<head>
<!-- html tags such as title, link, meta etc -->
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript" src="/path/to/plugin.js"></script>
<!-- more plugins included if required -->
</head>
<body>
<!-- html here -->
<!-- script is the last thing before the ending body tag (increases performance) -->
<script type="text/javascript" src="/path/to/your_jQuery_code.js"></script>
</body>
</html>
我认为担心javascript包含的服务器出行是不成熟的优化。 你有证据表明这些页面加载缓慢吗? 浏览器应该缓存javascript文件。
如果你确实有证据表明这是一个问题,你可以
- 将jquery代码和任何插件组合到一个文件中
- 写一个.net内容处理程序为你做这个(可能是矫枉过正)
然后,您可以每页添加一个自定义js文件来处理页面特定的属性。
您绝对可以将document.ready
和所有其他JavaScript代码放在外部文件中。
通常我有2个调用 - 一个用于jQuery本身,还有一个缩小的global.js文件,它结合并缩小了我的所有单个文件。
就个人而言,我喜欢使用前端搅拌机 ,但也有许多其他选择。
把document.ready
放在外部文件中已经没有错了。 事实上,这是我将我的js与html分开的方法。 如果您担心某些页面上运行的某些功能,您可以使用
var path = window.location.pathname;
if (path == "/yourdir/yourpage.html") {
//do something for this page only
}
或者您只能在某些页面上包含某些文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.