What are the Benefits and Drawbacks of script embedment [duplicate] - javascript

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.

Related

Javascript and CSS, inside HTML vs. in external file

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!

Is using inline JavaScript preferred to an external include if the script is really short?

I use External JavaScripts in a website as I always try to keep JavaScript at bottom and external.
But Google page speed is giving this suggestion
The following external resources have small response bodies. Inlining
the response in HTML can reduce blocking of page rendering.
http://websiteurl/ should inline the following small resources:
http://websiteurl/script.js
This external js file has only this content
$(document).ready(function() {
$("#various2").fancybox({
'width': 485,
'height': 691,
});
});
But in Yslow I get this suggestion
Grade n/a on Make JavaScript and CSS external
Only consider this if your property is a common user home page.
There are a total of 3 inline scripts
JavaScript and CSS that are inlined in HTML documents get downloaded
each time the HTML document is requested. This reduces the number of
HTTP requests but increases the HTML document size. On the other hand,
if the JavaScript and CSS are in external files cached by the browser,
the HTML document size is reduced without increasing the number of
HTTP requests.
Which is right Google or Yahoo?
This is a bit of a problematic example, on quite a few fronts.
You can organise your scripts in such a way that you do not need to inline that JS. For example you could have a common.js file that runs that snippet, other similar snippets and simplifies your code.
Additionally, this seems to have awoken "never inline any JavaScript EVER" architecture police. Turns out that sometimes it is a best practice to inline JavaScript, for example look at the common snippet from Google analytics.
Why are Google suggesting you should inline this tiny script?
Because 20% of the page visits you get have an unprimed cache
If you have a cache miss, it is likely a new connection to your site will need to be opened (1 round trip) and then the data delivered in the 2nd round trip. (if you are lucky you get to use a keepalive connection and it is cut to 1 round trip.
For a general "global" English web application you are looking at a typical 110ms round trip time for a service hosted in the US. If you are using a CDN the number would probably be halved.
Even if the resource is local, the web browser may still need to access the disk to grab that tiny file.
Non async or defer JavaScript script tags are blocking, if this script is somewhere in the middle of your page, it will be stuck there until the script downloads.
From a performance perspective if the only 2 options are:
Place a 50 char JavaScript bit inline
Place the 50 chars in a separate file and serve it.
Considering that you are a good web citizen and compress all your content, the amount of additional payload this adds is negligible compared to the 20 percent risk of giving people a considerable delay. I would always choose #1.
In an imperfect world it is very rare to have such a clear and easy set of options. There is an option 3 that involved async loading jQuery and grabbing this functionality from a common area.
Making scripts inline can have some detrimental effects -
a) Code organization - Your code gets scattered in between your markup, thus affecting readability
b) Code Minification and obfuscation becomes difficult
Its best to keep your js in seperate files, and then at build time integrate all of them into a single file, and minify and obfuscate this.
This is not quite true. You can configure the web server (well atleast apache) to make the scrips/ccs inlined when they are served.
Here is a useful link
http://www.websiteoptimization.com/speed/tweak/mod_pagespeed/
There are two factors to consider here. One is download time, the other is maintainability. Both of these are impacted by how many times a piece of Javascript is needed.
With respect to download time, you obviously have two choices: include the JS in the body of the page, or as an external file. Including the JS in the body does save an extra HTTP request, although it also bloats the HTML a bit and can be a pain to maintain if you have several scripts you're putting inline on several different pages.
Another important consideration is whether or not the JS is needed immediately on the page. If a small piece of JS is needed as soon as the page loads, then putting it inline may be a good idea. If it's being used for something asynchronous in the future, then putting it an external file may still be a good choice.
I usually write javascript inline, especially if the script is this small. I would say just paste it in your code. It won't increase the http document size by a lot.
While inlining the script will save a request, as Yslow suggests it increases the HTML document size, and mixes content/markup with code/logic, which you generally want to avoid from as much as possible.
The reason Yslow gives this caveat:
Only consider this if your property is a common user home page.
Is that if the page is loaded frequently, it's worth it to have the javascript external, since the files will be cached in the browser. So, if you combine your JS into one file, on the first request you incur one extra request, and on subsequent requests the file is loaded from the cache.
Aaron Peters talk from last year's Velocity EU gives a good insight into the options, and course you should choose - http://www.slideshare.net/startrender/fast-loading-javascript
For really small snippet of js it's really not worth putting them in an external file as the network overhead of retrieving them will dwarf the benefits.
Depending on the latency it may be ever worth including large scripts e.g. Bind mobile has loads of js in the first page loaded which it then cached in localstorage for later pages.
Addy Osmani recently put together a experimental library to help people play with caching scripts in localstorage - http://addyosmani.github.com/basket.js/

javascript basic question

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.

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.

Javascript file inclusion in html pages- what happens underneath in the browser?

I think this may be a browser dependent question- Suppose I have 10 Javascript files and several HTML pages. Suppose HTML pageA needs only JS1.js and JS3.js, similarly HTML pageB needs JS4.js and JS1.js. I want to know what would be effect of including all the 10 javascript files in all HTML pages? Will it directly relate to the memory consumption by the browser?
I am facing this problem particularly with YUI javascript library. There are several components like datatable, event, container, calendar, dom-event etc., The order in which they are included also seems to matter a lot- For example the dom-event js should be included before the rest for it to work. So to avoid all this confusion, I thought of including all these js files in a header file that gets included in all HTML pages.
The thing that I am worried about is the memory bloat and performance problems that it may cause. Please provide your suggestions on the same..
Thanks,
-Keshav
Any script you load into your page, even once downloaded and cached must still be parsed before the rest of the page can load. So in that sense there is a memory penalty, and there's still a potential for something in the script to significantly delay rendering.
However, in the case of a conscientiously designed library such as YUI I would expect the parsing time to be minimised.
If you can load all your scripts in at the end of the page, that can vastly improve performance as the entire page can render before being blocked by javascript execution, and your site will feel a lot snappier.
I would suggest investigating the Firebug Net panel and the YSlow extension to get specific performance stats for your website.
External scripts delay the display of the following html until they have loaded and executed. The impact is much less after the first page load, since they're already cached, though browsers will occasionally check for new versions, which still carries a delay. I try to limit the number of scripts and move the script tags to the bottom of the page when possible. Users won't notice the script loading delay if the page has already fully displayed.
if a given script does nothing, it will not affect the performance.
Obviously the first page will load slowly, but the rest will not need to load all the scripts because they will be cached. So the next pages will load faster
Tips:
1) Load the script at the bottom of the page (just before the closing BODY tag).
2) Use a non-blocking way of loading the scripts. This is the one I'm using .
<script type="text/javascript">
function AttachScript(src) {
var script = document.createElement("script");
script.type = "text/javascript";
document.getElementsByTagName("body")[0].appendChild(script);
script.src = src;
}
AttachScript("/js/jquery.min.js");
AttachScript("/js/ndr.js");
AttachScript("/js/shadowbox.js");
AttachScript("/js/libraries/sizzle/sizzle.js");
AttachScript("/js/languages/shadowbox-es.js");
AttachScript("/js/players/shadowbox-img.js");
AttachScript("/js/adapters/shadowbox-jquery.js");
Can't find the source web page though :-(
Memory Consumption:
Assuming the scripts are well written then memory consumption and performance issues should be nominal. Your biggest problem with including all scripts at once will be the latency in the user experience first time through, or if you make changes, because they will have to download all of them in one hit. I think you should only include the scripts you need per page, not all scripts at once.
You can assess the impact yourself using simple tools like task manager/processes in Windows to monitor memory/processor useage, or plugs ins like Firebug for FireFox.
You can also look into something called minification to help make your script files as small as possible.
Dependencies:
The order in which you include the scripts is important as some scripts may depend on functionality in other scripts. So if the code in one script attempts to run and it requires code in another script that has not been downloaded then it will fail. My advice would be to actually understand those dependancies in your scripts files rather than just downloading everything at once because it seems easier.
Use the YUI Configurator to help determine the required file includes and order, as well as how to use the Yahoo! CDN combo service to combine all YUI files into a single script tag.
http://developer.yahoo.com/yui/articles/hosting/
External assets to the HTML page are typically cached by the browser. External assets are anything requested from the HTML such as images, CSS, JavaScript, and anything else. So if you load all 10 script files up front you are forcing a one time massive download hit to your user. After this one time the user does not need to download the scripts again unless the modify timestamp on the files change.
Your page will only use what it requires. If a particular page requests js4.js and js5.js then all the functions in those files will be loaded into the interpreter in the order in which they are first requested from the HTML and second by the order in which they are specified in each of those files. If there are any namespace conflicts what ever is loaded into the interpreter last wins. The interpreter will clear out the functions once the page is unloaded from the browser.
For efficiency I would suggest using a server-side inclusion process to read each of the js files and include the contents of each file into a new single js file. This will reduce the number of HTTP requests to the server and save your users an extreme amount of bandwidth resources with regard to HTTP headers and GET requests. Also, put the request of this new one script file directly prior to the closing body tag of your HTML. Downloading of scripts block parallel downloads in IE, so you want to load scripts at the lowest possible point in the page.
Scriptaculous implements a nice way to handle js dependencies. Guess you could check it out and "re-implement" it. ;D
As for memory bloat and performance issues... as long as your JS doesn't leak a lot (YUI probably doesn't) memory won't be much of a problem, although it will make your pages load slower, especially if loaded in the header.
You can read on caching methods using PHP to pass on several javascript files as one big JS file which includes everything you need. For additional performance gains, you can make the browser cache the file locally in addition to sending it gzipped (if the browser has support for the encoding using something like ob_start("ob_gzhandler");). By using gzip encoding, you can severely reduce the filesize of the main JS file you're sending which includes all your JS code (since plain text compresses so well). I recently had to do this on my own website and it's worked like a charm for both JS and CSS files.
http://www.ejeliot.com/blog/72
Note that by following the instructions on that tutorial, your JS file will only be sent once and the browser on the client's machine will keep a local copy stored which will also improve performance of every visit thereafter.
Also, consider googling "Minify" which should be hosted on Google Code.

Categories

Resources