why use external javascript? - javascript

What are pros of using an external javascript file? I just can't figure it out, I see big websites using them all around several times instead of server-side includes. Is it just for caching?
If it's a matter of clean code and seperation of concerns, then you can still include it from the serverside into the html. For example I use SMARTY and I can just include the file {include file='javascript.js} inside <script></script> tages.
If it's for performance I can't see anything other than an extra http request that makes the external file slower involved. I'm sure I must be missing something because all the big websites still do this.
Is it because of caching the file? my javascripts are dynamic and shouldn't be cached anyway.
could someone help me out to make the right decision to choose what to do with my javascript files.
ps:can a 1.5K user create a tag for external-javascript?

The most important is that the file is cached by the browser. The fewer bytes that need to be sent from the server the better. This is a big part of web performance.
Second to that, it provides modularity.
I'm not sure why your JavaScript is dynamic, but I suggest you rewrite it in a way that removes that need. That in itself might be an issue for you down the road.

In your case where there is no caching because the entire javascript file is generated dynamically, inline is probably superior. It saves you the HTTP overhead.
Source: http://developer.yahoo.com/performance/rules.html#external

they also help the developers separate different conceptual areas of their code. It can get real annoying looking at hundred to thousands of lines of js in a single file, on top of complicated html.

Besides what #Gabriel said, it also helps you use the same function in different pages, withouth the need for them (.html docs) to be larger.

Related

If grouping front-end code helps reduce requests, why aren't more websites written on one html document?

I guess what I'm asking is that if grouping JavaScript is considered good practice, why don't more websites place the JavaScript and CSS directly into one HTML document?
why don't more websites place the JavaScript and CSS directly into one HTML document
Individual file caching.
External files have the advantage of being cached. Since scripts and styles rarely change (static) and/or are shared between pages, it's better to just separate them from the page making the page lighter.
Instead of downloading 500kb of page data with embedded JS and CSS, why not load 5kb of the page, and load from the cache the 495kb worth of JS and CSS - saves you 495kb of bandwidth and avoids an additional 2 HTTP requests.
Although you could embed JS and CSS into the page, the page will most likely be dynamic. This will make the page load a new copy all the time, making each request very heavy.
Modular code
Imagine a WordPress site. They are built using a tom of widgets made by different developers around the world. Handling that many code stuffed in one page is possible, but unimaginable.
if some code just short circuited or just didn't work on your site, it's easier to take out that code linking the external file, rather than scouring the page for the related code and possibly accidentally remove code from another widget.
Separation of concerns
It's also best practice to separate HTML from CSS and JS. That way, it's not spaghetti you are dealing with.
When you have a lot of code in a single document, it's harder to work with the code because you need more time to find the necessary string to change.
That is why it's good practice to divide code into separate files, with each of them solving its own special task, and then include them in code where it's necessary.
However, you can a write script which will join your files from the development version, which has many files, to a release version, which has fewer files, but this brings two problems:
People are often lazy to do additional coding to create this script and then change it when the structure of your project becomes more complex.
If you find a bug or add a small feature, you will need to rebuild your project again both in developed and release versions.
They separated them so that multiple webpages can use the same file. When you change a single file, multiple pages can aromatically updated also. In addition, big HTML file will cause a long time to download.

Is it beneficial to inline all JavaScript when deploying a website

In our HTML page, we have a list of tags to load in many (small) JavaScript source files.
For deployment we plan to concatenate the individual JavaScript files into one bundle which will be included in the HTML page, to save on 'expensive' HTTP requests.
But would it be even more beneficial, to just write all the JavaScript directly into the HTML file, in an in-line Javascript tag?
If the JavaScript code changes on every request ("tags"?), then yes, it's beneficial.
Otherwise: No, because the browser will not be able to cache the JS files.
the best way would be to concatenate them but don't put them directly into you html-file. that way the js-file can be cached independently from the (probably) changing html-source.
A file is better than writing the whole stuff into the HTML, as you can cache the javascript file coming from your server, but unless you cache all .html files, you won't get this benefit (i.e. browsers have to keep redownloading all the inline scripts inside your html files)
But would it be even more beneficial, to just write all the JavaScript directly into the HTML file, in an in-line Javascript tag?
No! You would increase the size of every request and destroy cacheability. One big (but external) JS file is the way to go.
Make sure the JS file is emitting the proper caching headers, and it will be loaded only once per client. Unless your JS is exceedingly small (and your description doesn't sound so), that's pretty much the optimum.
I'd suggest that you compile all your javascript into one file and load it with one <script> tag. Yes, HTTP requests take some time, and browsers limit number of concurrent requests (to one domain).
I wouldn't put all javascript in the HTML, because this is mixing logic and representation, prevents caching (of javascript), etc. Avoid this.
This is the general rule I follow: separate content that changes often from content that changes rarely. This way static content will be cached efficiently. And you can optimize "fluid" content (gzip, minify, etc.) so that it takes less time to load.
I'm assuming that you mean 'embed inside a <script> block' rather than in 'on*' attributes inside the HTML elements. If that's not the case, the answer is a definite no - 'on*' attributes are harder to maintain, and typically bad for accessibility.
Normally the answer is no, because although the user's first request will be more expensive if it has to get external resources, those resources will be cached so future requests will be cheaper. If you embed everything, the user has to load them every time they load the page.
So it depends on a few things, the most important of which are probably:
Are users browsing multiple pages? Will they return? If the answer to both questions is 'no', then there is no benefit from caching, so embedded JavaScript can be quicker.
Is the JavaScript static? If it's dynamic - as in, changes on every page load, then again, caching is irrelevant. You could probably improve your JavaScript architecture to separate the static bits from the dynamic.
You can mix the JavaScript so that static JavaScript is linked, while dynamic or page-specific JavaScript is embedded. This is especially useful with libraries - it may already be cached in the client from another site, but if not, you're still loading from a CDN like Google, so it's very quick.
I wouldn't have thought so.
I always just include files and try to keep my base html looking as clean as possible.
Die hards will say don't do it, separate content from styles and scripting, and I agree. But if its not a lot of JS, you may as well save on any additional HTTP requests. Yes, the browser won't cache it, but that's because it won't need to. And on an SEO basis, Page ranking is improved with faster page load, determined possibly on first visit, not after a cache.

Only running javascript required for current page, best methods?

So I know it's best to have one javascript file for an entire site to limit http requests. So obviously only some javascript is required for some pages. What is the best way of only running the javascript required for the current page?
EG.
if(page=='home'){
//run javascript require for the home page
}
Maybe this isn't an issue and if targeting elements are not found on the page javascript will just fail gracefully? I would just like to know the best practice for this javascript structure.
Encapsulate your logic in functions. Then just call the function(s) you need in each page, either via "onload" or an embedded function call in the page:
<script type="text/javascript">
yourFunctionForThisPage();
</script>
Edit: Just to clarify: my answer is assuming the (implied) constraint of a single .js file. As others have pointed out, although you save on HTTP requests, this is not necessarily a good idea: the browser still has to parse all the code in the file for each page, whether used or not. To be honest it's pretty unusual to have a global site-wide js resource with everything in it. It's probably a much better idea to logically split out your js into various files, i.e libraries. These libraries could be page-based - i.e specific code for a particular page, or algorithm/task-based that you can include in whatever pages need them.
Is this feasible?
While it is best to have just a single Javascript file per page to lower the number of requests yet it may not be feasible. Especially the way that you'd like to do it.
If you're asking how to join various scripts of various pages into a single script and then running just those parts that are related to a particular page then this is something you shouldn't do. What good is it for you to have one huge file with lots of scripts (also think of maintainability) compared to a few short integrated scripts? If you keep the number of scripts low (ie. below 10) you shouldn't be to worried.
The big downside is also that browser will load the complete script file which means it will take it more time to parse them as well as consume a lot more resources to use it. I'd strongly suggest against this technique of yours even though it may look interesting...
Other possibilities
The thing is that the number of Javascript files per page is low. Depending on the server side technology you're using there are tools that can combine multiple script files into one so every page will just request a single script file which will combine all those scripts that this particular page will use. There is a bit overhead on the server to accomplish this task, but there will be just one script request.
What do you gain?
every page only has scripts that it needs
individual script files are smaller hence easier to maintain
script size per request is small
browser parsing and resource consumption is kept low
Know what you will need on the page and use a script loader like labjs.
Also, remember that your specific case might be different from what others have found, so you might want to do some tests, to verify if, for example, having 5 little files, is better (or worse) than 1 big file.
The only way to be sure is to test different options yourself and come up with a fitting solution.

Loading Javascript : HTTP Requests -v- Asynchronous Loading

I'm having difficulty in deciding which approach is better in terms of site performance.
Either to have all required jQuery plugins in one file to be included on every page on the site OR split the plugins out to individual files and use the jQuery.getScript() method to load them as and when required.
Is there any real benefit in loading the scripts asynchronously over one http request?
All my Javascript will be minified and gzipped.
Thanks!
It's not so simple and depends on the distribution of javascript across your site. Have a look at this question : Which is better for JavaScript load-time: Compress all in one big file or load all asynchronously?
From my poit of view the best solution until now is controljs
Read the complete post http://www.stevesouders.com/blog/2010/12/15/controljs-part-1/
One request will be better for performance. Period. Only downside is, every time one of the files changes, the whole thing changes (and will have to be downloaded again). Plugins won't change much, so I'd put everything (as much as possible) in 1 file.
Put jQuery core in that file as well. And your custom javascripts as well. Just make sure it's in the right order :)
Try the YSlow plugin to Firefox and try your different setups.
That said, minifying your js to one file would be an easy way with great results. You will get one file, and it's often very much smaller than the sum of the parts.

Is there any good reason for javascript to be inline

I've been building a site. At some stage I noticed that IE display was a little broken and Chrome had all but rendered nothing but the body tag (empty), and FF all looked good.
After throwing my keyboard around the room and bashing my head against my mouse, I discovered the problem. I had left (don't ask how or why, must have been some lightning speed cut and paste error) an HTML comment unclosed in an inline script block.
<script type="text/javascript">
<!--
...
</script>
I'm guessing (not tested) the problem would have either not come up, or manifested itself in a far more noticeable way if the script was external. So anyways, I got to thinking, is there ever a time when you have a really good reason to write inline script??
No. Write Unobtrusive Javascript.
If you want your Javascript to run as early as possible, it might make sense to include inline Javascript, since it will run before any other HTTP requests have necessarily completed.
And in some cases, you're including Javascript from a 3rd party provider and you don't really have a choice. Certain ad systems, as well as Google Analytics, spring to mind.
If the script must be dynamically generated (say by a PHP or ASP.NET MVC page) would be one reason to have it inline :-)
Depends on how much JS do you plan to write. If you're writing many support routines (lots of validation checks, text processing, animation and effects) then it makes sense to have the code in a separate file. This allows code reuse and removes a lot of junk from your HTML page.
On the other hand, there is no need to put 10 lines of code, or a single function (a refresh JS comes to mind) in a separate file. It will also load slightly faster, since the browser does not need to make an additional HTTP request to download the separate JS file.
Most XSS vulnerabilities can only be exploited using inline javascript.
It's not necessarily enough of a reason, but the pages will load faster. To this end, sometimes, even when you write the script in another file, you want it to show up as inline on the client side.
I sometimes place javascript inline in pages that get partially reloaded (to bind some events to newly added form-fields for example) and / or pages that use some unique javascript that I will not use on any other page.
Having many external scripts can ultimately slow down the page as the browser must call each file separately. Combining the JavaScript into one file or into the page itself can sometimes alleviate this problem.
On the other hand, I believe the browser may cache a script file once it's been called for the first time so if you have a lot of the same code across your site, external is the way to go.
I work a good deal in something called Flex, which combines XML and ActionScript to create the final bytecode. It is ALWAYS best practice to separate the two as much as possible. That way, you can very clearly and easily separate the View (the HTML or MXML in my case) from the Controller (the script)
It also means that you do not have to worry about looking through five files for one line of code -- all of your code is in one place.
File caching is the reason to have external js and css files. Even if you only have one HTML page, this page is likely to be updated often and so will be downloaded by the browser as often. If the js (and css) are in the HTML page, that too will be downloaded often. Keeping them separate will keep the HTML file smaller and will download faster. The js and css files will have been cached so will not be continually downloaded. That is assuming these files are not updated very often.

Categories

Resources