Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - How do you convert the $(document).ready() into a js file?

Tags:

jquery

I have a ton of jquery code in the .ready()

 $(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?

I read this post: Enclosing external jQuery file in $(document).ready()

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?

Thanks!

like image 647
EKet Avatar asked Nov 14 '11 05:11

EKet


2 Answers

Step 1. Create file myfile.js with contents:

$(document).ready( function() { 
       // .... your jQuery goodness .... 
 });

Step 2. In your HTML page, first include jQuery, then include myfile.js (in that order).

<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!

Step 4. (OPTIONAL) Minify your myfile.js using http://jscompress.com/ or whatever else minifier you want to use.

like image 154
Strelok Avatar answered Oct 14 '22 07:10

Strelok


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/

like image 28
Thanh Nguyen Avatar answered Oct 14 '22 07:10

Thanh Nguyen