2

Quick question, I have some scripts that only need to be run on some pages and some only on a certain page, would it be best to include the script at the bottom of the actual page with script tags or do something like in my js inlcude;

var pageURL = window.location.href;

if (pageURL == 'http://example.com') {
     // run code
}

Which would be better and faster?

7 Answers 7

4

The best is to include the script only on pages that need it. Also in terms of maintenance your script is more independant from the pages that are using it. Putting those ifs in your script makes it tightly coupled to the structure of your site and if you decide to rename some page it will no longer work.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes but on Yslow and google PageSpeed it says that all js should be in one external file, as it can and will significantly decrease page load speed.
@nvcode, that's true, but you really should not be putting everything into a single huge javascript file. While this might increase performance for visitors that already have it in cache it will significantly decrease performance for first time users that are hitting the home page for the first time. You really have to find the right balance when segmenting your scripts. Jeff wrote a very nice blog post about this.
On my homepage I add all the css and js directly into the page, then download the external css, and js dynamically for other pages once the page has been loaded. So that shouldn't matter, with that in mind does it matter using if statements in my jquery? Thanks by the way
@nvcode, as I said in my answer I wouldn't write such an if in any javascript file: if (window.location.href == 'http://example.com'). It's so brittle that I really would avoid it.
3

I can recommend you to use an asynchrounous resource loader, LAB.js for example. Then you could build a dependencies list, for instance:

var MYAPP = MYAPP || {};

/*
 * Bunches of scripts
 * to load together
 */
MYAPP.bunches = {
    defaults:       ["libs/jquery-1.6.2.min.js"],

    cart:           ["plugins/jquery.tmpl.min.js",
                     "libs/knockout-1.2.1.min.js",
                     "scripts/shopping-cart.js"],

    signup:         ["libs/knockout-1.2.1.min.js",
                     "scripts/validator.js"]
    /*
    ... etc
    */
};

/*
 * Loading default libraries
 */
$LAB.script(MYAPP.defaults);

if (typeof MYAPP.require !== 'undefined') {
    $LAB.script(MYAPP.dependencies[MYAPP.require]);
}

and in the end of your page you could write:

<script type="text/javascript">

    var MYAPP = MYAPP || {};
    MYAPP.require = "cart";

</script>

<script type="text/javascript" src='js/libs/LAB.min.js'></script>
<script type="text/javascript" src='js/dependencies.js'></script>

By the way, a question to everyone, is it a good idea to do so?

2 Comments

Yes but using these extra external js, will decrease loadtime even further making the function of the program nearly useless.
@nvcode, I suggest this approach only for “semi-large„ apps, where large and completely different pieces of code need to be assembled without a server-side help.
1

In so far as possible only include the scripts on the pages that requirement. That said, if you're delivering content via AJAX that can be hard to do, since the script might already be loaded and reloading could cause problems. Of course you can deliver code in a script block (as opposed to referencing an external js file), in code delivered via AJAX.

In cases where you need to load scripts (say via a master page) for all pages, but that only apply to certain pages, take advantage of the fact that jQuery understands and deals well with selectors that don't match any elements. You can also use live handlers along with very specific selectors to allow scripts loaded at page load time to work with elements added dynamically later.

Note: if you use scripts loaded via content distribution network, you'll find that they are often cached locally in the browser anyway and don't really hurt your page load time. The same is true with scripts on your own site, if they've already been loaded once.

Comments

1

You have two competing things to optimize for, page load time over the network and page initialization time.

You can minimize your page load time over the network by taking maximum advantage of browser caching so that JS files don't have to be loaded over the network. To do this, you want as much javascript code for your site in on or two larger and fully minimized JS files. To do this, you should put JS for multiple different pages in one common JS file. It will vary from site to site whether the JS for all pages should be ine one or two larger JS files or whether you group it into a small number of common JS files that are each targeted at part of your site. But, the general idea is that you want to combine the JS code from different pages into a common JS file that can be most effectively cached.

You can minimize your page initialization time by only calling initialization code that actually needs to execute on the particular page that is being displayed. There are several different ways to approach this. I agree with the other callers that you do not want to be looking at URLs to decide which code to execute because this ties your code to the URL structure which is better to avoid. If your code has a manageable number of different types of pages, then I'd recommend identifying each of those page types with a unique class name on the body tag. You can then have your initialization code look for the appropriate class on the body tag and branch to the appropriate initialization code based on that. I've even seen it done where you find a class name with a particular common prefix, parse out the non-common part of the name and call an initialization function by that name. This allows you to give a page a specific set of behaviors by only adding a classname to the body tag. The code remains very separate from the actual page.

the less general purpose way of doing this is to keep all the code in the one or two common JS files, but to add the appropriate initialization call to each specific page's HTML. So, the JS code that does the initialization code lives in the common JS files and thus is maximally cached, but the calling of the appropriate initialization code for that page is embedded inline in each specific page. This minimizes the execution time of the initialization, but still lets you use maximal caching. It's slightly less generic than the class name technique mentioned earlier, but some may like the more direct calling technique.

1 Comment

Thank you for explaining this in detail
0

Include scripts at bottom of pages that need it only.

Comments

0

The YSlow add-on is the best solution to know why your website is slow.

enter image description here

There are many issues which could be the reason for slowness.

Combining many jQuery to one could help you increasing your performance.

Also you can put the script at the bottom of your page and CSS at top.

1 Comment

Both are different Yslow is an add-on
0

Its basically up to you and depends on what the code is.

Generally with small things I will slip it into the bottom of the page. (I'm talking minor ui things that relate only to that page).

If you're doing the location ref testing for more than a couple pages it probably means you're doing something wrong.

You might want to take a look at one of these:

And as for which is faster it's wildly negligible, pick what is easier for you to maintain.

1 Comment

I have a couple of if statements in my external js, but I just wondered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.