Jquery - 你如何将 $(document).ready() 转换成一个 js 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8117765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery - How do you convert the $(document).ready() into a js file?
提问by EKet
I have a ton of jquery code in the .ready()
我在 .ready() 中有大量的 jquery 代码
$(document).ready(function() {
//jQuery goodness in here.
How do I take all the code and just make it a .js file so I can just reference the script like any other script? Should i minify it? How do I do that?
我如何获取所有代码并将其设为 .js 文件,以便我可以像引用任何其他脚本一样引用该脚本?我应该缩小它吗?我怎么做?
I read this post: Enclosing external jQuery file in $(document).ready()
我读过这篇文章:在 $(document).ready() 中包含外部 jQuery 文件
But it didn't help because I'm not sure how to actually implement it. Do I just copy the code exactly how it is and save it as a .js file? Then what about the minify process?
但这没有帮助,因为我不确定如何实际实施它。我是否直接复制代码并将其保存为 .js 文件?那么 minify 过程呢?
Thanks!
谢谢!
回答by Strelok
Step 1.Create file myfile.jswith contents:
步骤 1.使用内容创建文件myfile.js:
$(document).ready( function() {
// .... your jQuery goodness ....
});
Step 2.In your HTML page, first include jQuery, then include myfile.js (in that order).
步骤 2.在您的 HTML 页面中,首先包含 jQuery,然后包含 myfile.js(按此顺序)。
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript" src="myfile.js"></script>
Step 3.PROFIT!
第 3 步。利润!
Step 4. (OPTIONAL)Minify your myfile.jsusing http://jscompress.com/or whatever else minifier you want to use.
步骤4.(可选)缩减大小的myfile.js使用http://jscompress.com/或任何其他minifier要使用。
回答by Thanh Nguyen
You can write all your codes in a function and call it when dom's ready. Minify is recommended for make you js smaller -> faster loaded. You can find many online js compressors, such as http://www.refresh-sf.com/yui/
您可以在一个函数中编写所有代码,并在 dom 准备好时调用它。建议使用 Minify 使您的 js 更小 -> 加载速度更快。网上可以找到很多js压缩器,比如http://www.refresh-sf.com/yui/