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.
Related
I have a few snippets of javascript scattered about my pages - many are contained in my own .js files, however some of the stuff that I've found online sits directly on the page.
I'm not too familiar with how javascript interacts with a page - is there a difference between adding the script inline or adding a reference to the external file?
There is little difference in using one or the other way. The real difference comes from the advantages/disadvantages that each one has.
Inline scripts
Are loaded in the same page so is not necessary to trigger another request.
Are executed immediately.
The async and defer attributes have no effect
Can be helpful when you are using a server-side dynamic rendering.
External scripts
Gives better separation of concerns and maintainability.
The async and defer attributes have effect so if this attributes are present the script will change the default behavior. This is not possible with inline scripts.
Once a external script is downloaded the browser store it in the cache so if another page reference it no additional download is required.
Can be used to load client code on demand and reduce overall download time and size.
External script files
Much easier to analyse so you can debug more efficiently and read it. This makes life much easier for us as programmers
Download time is reduced as the external file is cached so it can be downloaded with the website
Instead of writing the same script numerous times, an external file can be called and executed anywhere in the code
External files decrease page rendering speed as the browser has to stop parsing and download the external file. This adds a network round trip which will slow everything down. Also because external files are cached it makes it tough to delete them if the have been updated
Inline code
Inline code reduces the number of HTTP requests making improving the performance of the webpage. This because the code is loaded in the same page so a request is not needed
Inline script is executed immediately
Although inline code is much harder to read and analyse as it just looks like a lump of code chucked together. It is hard work having to find the problem when debugging, making life as a programmer tough
Hope this helps you understand a bit more :)
Looking at the <script> tag documentation, you can see that you can use the async and defer attributes only with external scripts, which might have an effect on scripts that do not use event listeners as entry points.
Other than that, inlining renders a browser unable to cache it on its own, so if you use the same script on different pages, the browser cache cannot kick in. So it might have an effect on performance and/or bandwidth usage.
And, of course, splitting code up into files is one way of organizing it.
Generally there is no difference as indicated in the comments. But, if the snippet is embedded in the middle of the HTML in the page and it is not a function, it is executed immediately. Such script segments may have a difference in behavior when moved to a separate JS file when enough care is not taken.
Is there any difference between including external javascript and CSS files and including all javascript and CSS files (even jQuery core!) inside html file, between <style>...</style> and <script>...</script> tags except caching? (I want to do something with that html file locally, so cache doesn't matter)
The difference is that your browser doesn't make those extra requests, and as you have pointed out, cannot cache them separately from the page.
From a functional standpoint, no, there is no difference once the resources have been loaded.
The reason most of the time we see external path for CSS and javascript because they are either kept on a CDN or some sort sort cache server now days on a cloud
Very good example is when you include jquery from google
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
here we see that google is hosting it for us and we don't need to worry about maintainance etc
So if you want to keep them locally then you will have to maintain it
There isn't any difference once the code is loaded. Of course it wont be cached like you pointed out but since you just need to do something locally, it really isn't that important.
On thing to remember would be that you'd have to make sure dependency chains aren't broken since the browser would be loading the scripts simultaneously.
Edit: Of course your main page would appear to take a longer time to load since it has to download all that extra content before the <body> starts to load. You can avert that by moving your JS at the bottom (near the footer) instead.
When your css isnt loaded your page appears crappy at first and then it settles after the css styles are applied, thus now you have to declare your css style on top of the page and then wait for all that to be processed by the browser and then start rendering your page or you let your first page load slowly and on further requests your page will load quicker since the style is now cached
and similarly with your script code, now you need to wait for your code to be rendered on the page and then wait for the the execution that you have bound in $(document).ready().. I hope you realize that $(document).ready will now be delayed since there is no caching.
There is a huge performance issue with this. your load and DOMContentLoaded will fire way slower.
load will fire when browser parses last line of your code. So browser will show waiting circle until all your resources are loaded and parsed. Browsers load multiple resources synchronously. You will lose this performance boost by including JS and CSS code in HTML.
No difference on the client side except you'll do less requests, thus loading faster. On the other hand, you won't be caching but you also won't be able to share the style an the JavaScript among several pages.
If you're positive that CSS and JavaScript are only going to be used in this page, inline is fine IMO.
If you use the script and css only on one page, including them in the html would be the fastest way as the browser needs to make only one request. If you use them on more pages, you should make them external so the browser can cahche them and only has to download them once. Using the jquery from google for example, as mentionned #hatSoft, is even better as the browser is very likly to have them already in cache from othersites that reference them when your user visits for the first time. In real live you rarly use scripts and css on one page only, so making them external is most often the best for performance, and definitly for maintenance. Personaly i always keep HTML, js and css strictly separate!
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.
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.
While declaring Javascript in a html document. We have 3 ways to do that
script section goes in the head tag
script section goes in the body tag
javascript is references from an external file
Which one of these is faster and efficient with respect to performance is considered?
Thanks
Put javascripts/references to linked scripts at bottom of page if possible. As suggested here: http://developer.yahoo.com/performance/rules.html
1 and 2 are about tag location. 3 could apply to both 1 and 2.
In addition, you can have javascript in event handler attributes, like so:
<button onclick="alert(1)">pressme</button>
to top it off, you can also have javascript as url, in for example links:
click me
Just sticking to your examples: first of all, it is usually a good idea to use external script files that you load with a src component in tags. This allows the browser to cache the script, which allows the page to load faster after the initial page load. this is especially true if you use things like jQuery and load them from a public Conent delivery network (like the google ajax api see: http://code.google.com/apis/ajaxlibs/documentation/)
As for the location (head or body): in the olden days, people used to say, put your scripts in the head to ensure they are loaded once the body is loaded and all the interactive elements can be used by the user. But the problem with that is that the loading of those scripts will block loading of the visual part of the page, the body. Basically, the users are looking at a blank page, wondering whuy their page is taking so long to render.
So nowadays, the popular wisdom is to put all scripts as far down in the body as you can, and make sure that you write your javascript in a way that it can handle partially loaded scripts. The YSlow guide is a great resource to learn about these things. see:
http://developer.yahoo.com/yslow/help/
It really depends on what type of JavaScript you are writing. If you writing code that needs to be executed in the body (for ex: document.write()) you will have to write that in the body tag. If that is not the case and if you are writing javascript functions then should go in the head tag or in a different file. You would use a different file if you are going to use the same functions across many pages.
w.r.t performance, it again depends on what you are doing. If you have just one page that uses javascript, it would be faster to keep it in the header. This way you would reduce a round trip to get the javascript file.
If you have multiple pages that use the same functions, then it will be faster if the functions are in a different file because they will be downloaded once and used multiple times.
I'd say it depends on the circumstances.
An external file is a good idea if you have a large script that is used across a site and you want to take advantage of client-side caching mechanisms.
If a script is only used on one page then keeping it in the head/body might make sense. Clearly the earlier the script comes in the page the sooner the JavaScript will be executed, but you may be constrained by waiting for the DOM to be available to the script anyway, in which case it won't make any difference if it's in the head or the body.
You could put the script immediately after any HTML that defines the DOM that it needs access to. This would probably be the quickest way of getting a script to execute in the page, but don't go for this over an externally loaded (and cached) file if it is large or used in many places.
If you're super concerned about performance, I would say loading the js in the html would be fastest. Items in the load before the rest of the page, so from a user's perspective, they may think the download takes longer with js since the page won't start to render until after the is loaded, but the amount of data should be the same. External js file is likely the slowest since it will require a separate http request.
The short answer is...well...it depends.
If by
faster and efficient with respect to performance is considered
you mean "loads faster", then inline script in the head will get your code into the browser faster the first time it's loaded. An external file can be cached, so if you're including the same script in multiple pages, once you overcome the overhead of loading it the first time, then you have it resident in memory.
I prefer to have my Javascript and HTML all in the same file just because I don't like having a lot of different tabs open. But then again it is a lot neater to use your Javascript, HTML, and CSS all in different files.
So far, the more complicated/long the code is, I'd use a different file, but if the code is simple, I'd just use the same file for everything.