Reputation: 11059
I read several articles saying it is not recommended to put javascript code within the page.
I would like to hear from you. How do you do with that code that is specific to that page?
In my Project.cshtml I have:
<script type="text/javascript">
$(document).ready(function () {
$('.project-status').parent('a').click(function (e) {
e.preventDefault();
DoSomething();
});
});
</script>
Have in my myfunctions.js file:
function DoSomething() {
alert('test')
}
On every page of my project, this situation repeats itself.
You make a single file .js
and put there all the javascript for all pages?
Or make one file per page, and make reference that file on the page?
Or put the js code that is specific to the page in the page itself?
I had this question for I am with the following problem:
In my application I have:
Project.cshtml
When you click a link, load the page ProjectPhotos.cshtml via ajax into a div#photos
The problem is that on my page ProjectPhotos.cshtml have the script:
<script type="text/javascript">
$(document).ready(function () {
$('.project-status').parent('a').click(function (e) {
e.preventDefault();
DoSomething();
});
});
</script>
As this page is loaded via ajax, this script will not in the HTML markup.
If this script was in a separate JS file, click on the link, I could load the file dynamically.
Thank you all for your help!
Upvotes: 3
Views: 2023
Reputation: 6334
Probably the best way is to put everything in one file for two reasons. One maintenance is easier there is only one script to deal with instead of searching through seven. Second once the script is loaded it is cached. Meaning it is ready for all your other pages as well. Assuming you don't have scripts that are huge for each individual page the overhead is not really that much.
Upvotes: 0
Reputation: 5119
It depends. If the scripts are fairly small, concatenating the files into one is better because you reduce the number of connections (the browser will usually use just a few simultaneous connections).
But if the scripts are big, and the scripts are not needed on all pages, it's probably better to split it up. But still preferably only one file per page.
Try both options and disable/empty cache in your browser and test...
Upvotes: 2