Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One JavaScript File Per Page or Combine when using Jquery and Document Ready Function

Ok So I know it always depends on the situation but I have, thus far, combined my jquery files/plugins into a single compressed file.

Now I am wondering what I should do with my page specific js/jQuery code. Should I have a single file with one Document.Ready function and my entires sites js code inside of it? Or split it up into seperate js files per page with a document ready call in each?

These files will inclide things such as .Click handlers and other jquery code specific to certain pages.

Whats the best practice here to optimize load times and maintainabilty?

like image 792
stephen776 Avatar asked Feb 28 '11 17:02

stephen776


People also ask

Can we use multiple document ready () function on the same page?

Yes we can do it as like I did in below example both the $(document). ready will get called, first come first served.

Can you use both jQuery and JavaScript together?

Implementing Your Own jQuery and JavaScriptThe JavaScript code can be added inside the <script> element, or the src attribute of the <script> element can point to the location of a separate JavaScript document. Either way, the JavaScript will be loaded in the same manner.

Is document ready JavaScript or jQuery?

$( document ).ready() jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

Should I put all my JavaScript in one file?

To avoid multiple server requests, group your JavaScript files into one. Whatever you use for performance, try to minify JavaScript to improve the load time of the web page. If you are using single page application, then group all the scripts in a single file.


1 Answers

One way to do it would be to use require.js and then have an array with files and page types. Give each body tag an ID and use it to reference what files should be loaded in.

<body id="pageName">

Keep your global files everything you need for the core functionality to work and then lazy load in the features that aren't required for your site to run faster. I've seen huge speed improvements from this technique.

http://requirejs.org/

like image 93
Seth Avatar answered Oct 17 '22 17:10

Seth