Only one file `.js` per page is recommended? - javascript

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?
Sample
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.
Question
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?
The problem we want to solve
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!

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

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.

Related

Less: `modifyVars` on files loaded after document loaded

My page uses Less files that are compiled on the client side. I want to load some of those files after page finished loading.
I tried the "Less in the browser" way, but it seems to only work for files that were originally declared in the head part of the page. Declarations I add later (from Javascript) are not processed by the Less...
Another way I tried was "Programmatic Usage", but in this case I have to inject the CSS code myself. It means I cannot use less.modifyVars() any more to change styling later (or I have to trigger recompilation myself and then replace the generated CSS, which I want to avoid).
I like the first way more, but I don't know how to load files after page finished initial loading. Maybe there is a function to load Less file?
Thank you!
I think I found solution:
less.registerStylesheets().then(
function () {
less.refresh();
}
);
First function will reread declarations. The second one will recompile all files (actually not very good).

How to add javascript to php page

I see a lot of script adding Javascript to their webpages in different ways and am trying to figure out the correct way to do it. For example, in the header of one of the php scripts I use it has this:
<script type="text/javascript" src="/javascriptfile.js"></script>
<script type="text/javascript">
var stuff = "file.php";
var ip_add = '32.42.42.442';
</script>
What I don't understand is why would you ever put the full javascript code in the header instead of just including it within a file. For example, why not move the javascript mentioned about into it's own file and just just use this in your header:
<script type="text/javascript" src="/javascriptfile.js"></script>
<script type="text/javascript" src="/javascriptfile2.js"></script>
Are there certain times you should have the full javascript displayed in the page source instead of just linking to it in its own javascript file?
What I don't understand is why would you ever put the full javascript code in the header instead of just including it within a file.
It costs you caching. This is a long term penalty. The impact of that depends on how often the script will be used by the browser
It saves you an HTTP request. This is a short term bonus. It saves you a bit of time when loading the script in the first place.
This has nothing to do with PHP though. It applies to any HTML document.
Some of this is "legacy". At one point, you HAD to put <script> tags in the <head> portion of your markup, and so this is where most examples put it.
If you add a src reference to an external file, you can reuse the script as a resource on other pages that call for this. If you are using the same script all over the place, put it in a "js" directory and the browser won't fetch a new copy each time. This helps with bandwidth.
If, however, you add the raw script to your page, the whole page (minus images and other "embedded" content) will arrive in one thread. This helps with load times.
Unless you're expecting 10,000+ pageviews in a short space of time, I wouldn't worry too much either way.
Oh, and one other thing to consider: http://developer.yahoo.com/performance/rules.html#js_bottom -- why you should put your scripts at the bottom of your document.
I totally agree with #Quentin. Additionally I would suggest putting your scripts in seperate .js files and include them - for reasons of structuring - not only in large projects.
One thing that could lead you to put the JS code into a .php file however could be if you need to generate code using PHP or if you want to use information that is e.g. pulled from a database directly like this:
<?php
$foo = getSomeInformation();
?>
<script type="text/javascript">
var someVar = <?=$foo?>;
</script>

Including javascript files

I'm finishing my project right now and see that I've got a lot of javascript code on each page. It's not included as a ".js" file, but rather coded in the page itself. I figured it's a bad idea, so now I'm trying to put them all in one .js file and include it in each page.
The only problem I'm facing now is this: Some functions are only called on certain pages and are depending on the inclusion of jquery plugins. Not all pages needs the plugin however.
Example:
On the home page I need to chain the Country dropbox with the City dropbox, thus I need the jchained.js plugin for jquery. The code I need to use is:
$(function(){
$("#city").chained("#country");
});
When I add this function to the .js file, and I open a page where I don't need to chain the dropboxes I get logically an error:
TypeError: $("#city").chained is not a function
So if I understand this correctly, in order to use a .js file with all my different functions for different plugins, I need to include all the plugins to all the pages?
Thanks for your ideas & help.
Personally, I don't think you should worry about including alot of .js files, that's part of web development. Another option, albeit slightly more tedious, is you can make a check for the function to exist (if the plugin .js has been included) and then call it if it does:
if(typeof yourFunctionName == 'function') {
yourFunctionName();
}
It completely depends on how the code is structured or how complex the current code is.
An immediate solution will be,
Give an id to each page (may be on body tag).
Put all the code in a single external JavaScript file.
Execute the code meant for that particular page only if it has required id on that body element.
Something like :
if ( $('body').attr('id') == "home" ) {
/* Add home page JS here */
}
You can try this.
Correct me if I am wrong.

How to write javascript code using external files only

When using HTML5 Boilerplate, you are given a script.js file and the jquery file are all loaded after the body.
How do I know when to call certain code for a specific page? For eg. What if on /maps I want to load google maps dynamically, how do I accomplish this without putting it on the page and using script.js file while having it not load the map for all pages?
Basically, how do I structure my code when I can't have any script in my pages? How do I know what code to call for a particular page?
Script files that are included are immediately executed, so inside the script file you could have a section check the URL of the page you're on.
For example, something like this:
if (window.location.href === "http://myapp.com/maps") {
// call the map function or whatever ...
}
But, out of curiosity, why can't you add a script file to the specific page you're on? I'd only recommend the solution above if you absolutely cannot edit the HTML of your pages.
I too have the same question. I searched and just found these two
http://paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-execution/
http://www.viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution/
I am going through of this, and not yet completely reviewed. See if it is useful to you in between.

Jquery: how to register an event on all pages?

I want to run the following jquery code on every page in my website.
$(document).ready(function(){
$("#more").click(function(){
$("#morediv").slideToggle("slow");
return false;
});
});
In all my pages I have the more and morediv elements defined, for every page I have different js file and adding this code in every file will not be a good solution (I suppose).
I have created a global.js to include this code, but in other pages also I have the $(document).ready(function(){} function defined and may be that's why its conflicting and not running properly.
You can have multiple $(document).ready(function(){}) elements on your page, so that it's the problem. I suggest using Firefox/Firebug and examining any console errors you find to discover the problem. Perhaps your global.js file is being loaded before jQuery itself? Otherwise, you'll need to dig into it with Firebug's debugger.
Are you actually doing some server-side programming or you are talking about plain HTML pages. I would advise that you have templates (this is specific to your development environment and tools of choice) and include the JS in those templates. Then the actual pages will all use the template and have the JS available. The question you are asking has in fact nothing to do with Javascript or JQuery, but the way you organize your site... unless I'm missing something.
having $(document).ready() event handler in global.js and the page it is included in does not poses any problem I'm using it and it works really fine.
Just a guess, but are you referencing the location of the global.js file correctly?
To be sure, write something like the following into your global script:
$(document).ready(function(){
alert("document ready");
$("#more").click(function(){
$("#morediv").slideToggle("slow");
return false;
});
});
If you don't get the alert the script is not pathed correctly, or is not placed after the jquery include (or the jquery include is not pathed properly).

Categories