Javascript and CSS, inside HTML vs. in external file - javascript

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!

Related

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

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.

What are the pros and cons of adding <script> and <link> elements using JavaScript?

Recently I saw some HTML with only a single <script> element in its <head>...
<head>
<title>Example</title>
<script src="script.js" type="text/javascript"></script>
<link href="plain.css" type="text/css" rel="stylesheet" />
</head>
This script.js then adds any other necessary <script> elements and <link> elements to the document using document.write(...): (or it could use document.createElement(...) etc)
document.write("<link href=\"javascript-enabled.css\" type=\"text/css\" rel=\"styleshet\" />");
document.write("<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js\" type=\"text/javascript\"></script>");
document.write("<script src=\"https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js\" type=\"text/javascript\"></script>");
document.write("<link href=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.0/themes/trontastic/jquery-ui.css\" type=\"text/css\" rel=\"stylesheet\" />")
document.write("<script src=\"validation.js\" type=\"text/css\"></script>")
Note that there is a plain.css CSS file in the document <head> and script.js just adds any and all CSS and JavaScript which would be used by a JS-enabled user agent.
What are some of the pros and cons of this technique?
The blocking nature of document.write
document.write will pause everything that the browser is working on the page (including parsing). It is highly recommended to avoid because of this blocking behavior. The browser has no way of knowing what you're going to shuff into the HTML text stream at that point, or whether the write will totally trash everything on the DOM tree, so it has to stop until you're finished.
Essentially, loading scrips this way will force the browser to stop parsing HTML. If your script is in-line, then the browser will also execute those scripts before it goes on. Therefore, as a side-note, it is always recommended that you defer loading scripts until after your page is parsed and you've shown a reasonable UI to the user.
If your scripts are loaded from separate files in the "src" attribute, then the scripts may not be consistently executed across all browsers.
Losing browser speed optimizations and predictability
This way, you lose a lot of the performance optimizations made by modern browsers. Also, when your scripts execute may be unpredictable.
For example, some browsers will execute the scripts right after you "write" them. In such cases, you lose parallel downloads of scripts (because the browser doesn't see the second script tag until it has downloaded and executed the first). You lose parallel downloads of scripts and stylesheets and other resources (many browsers can download resources, stylesheets and scripts all at the same time).
Some browsers defer the scripts until after the end to execute them.
The browser cannot continue to parse the HTML while document.write is going on and, in certain cases, when the scripts written are being executed due to the blocking behavior of document.write, so your page shows up much slower.
In other words, your site has just become as slow as it was loading on a decades-old browser with no optimizations.
Why would somebody do it like this?
The reason you may want to use something like this is usually for maintainability. For instance, you may have a huge site with thousands of pages, each loading the same set of scripts and stylesheets. However, when you add a script file, you don't want to edit thousands of HTML files to add the script tags. This is particularly troublesome when loading JavaScript libraries (e.g. Dojo or jQuery) -- you have to change each HTML page when you upgrade to the next version.
The problem is that JavaScript doesn't have an #include or #import statement for you to include other files.
Some solutions
The solution to this is probably not by injecting scripts via document.write, but by:
Using #import directives in stylesheets
Using a server scripting language (e.g. PHP) to manage your "master page" and to generate all other pages (however, if you can't use this and must maintain many HTML pages individually, this is not a solution)
Avoid document.write, but load the JavaScript files via XHR, then eval() them -- this may have security concerns though
Use a JavaScript Library (e.g. Dojo) that has module-loading features so that you can keep a master JS file which loads other files. You won't be able to avoid having to update the version numbers of the library file though...
One major disadvantage is browser incompatibility. Not all browsers correctly fetch and incorporate the resources into the DOM, so it's risky to use this approach. This is more true of stylesheets than scripts.
Another issue is one of maintainability. Concatenating and writing strings to add DOM elements on the client'side can become a maintenance nightmare. It's better to use DOM methods such as createElement to semantically create elements.
One obvious advantage is that it makes conditional use of resources much easier. You can have logic that determines which resources to load, thereby reducing the bandwidth consumption and overall processing time for the page. I would use a library call such as jQuery $.getScript() to load scripts versus document.write. The advantage being that such an approach is cleaner and also allows you to have code executed when the request is completed or fails.
Well, I may as well throw my hat in the ring on this one...
If you examine google's closure library, base.js, you will see that document.write is used in their writeScriptTag_() function. This is an essential part of the dependency management system which 'closure' provides, and is an enormous advantage when creating a complicated, multi-file, library-base javascript application - it lets the file/code prerequisites determine loading order. We currently use this technique and have been having little trouble with it. TBH, we have not had a single issue with browser compatibility, and we test regularly on IE 6/7/8, FF3/2, Safari 4/5 and Chrome latest.
The only disadvantage that we have had so far is that it can be challenging to track down issues caused by loading a resource twice, or failing to load one at all. Since the act of loading resources is programmatic, it is subject to programmatic errors, and unlike adding the tags directly to the HTML, it can be hard to see what the exact loading order is. However, this issue can be largely overcome by using a library with some form of dependency management system such as closure, or dojo.
EDIT: I have made a few comments to this nature, but I thought it best to summarize in my answer:
There are some problems with dojo.require() and jQuery.getScript() (both which ultimiately perform an ajax request and eval).
loading via ajax means no cross scripting - ie no loading javascript that is not from your site. This will be a problem if you want to include https://ajax.googleapis.com as listed in the description.
Eval'd scripts will not show up in a javascript debugger's list of page scripts, making debugging quite challenging. Recent releases of firebug will show you eval'd code, however filenames are lost making the act of setting breakpoints tedious. AFAIK, Webkit javascript console and IE8 developer tools do not show eval'd scripts.
It has the advantage that you don't need to repeat the script references in each HTML file. The disadvantage is that the browser must fetch and execute the main javascript file before it may load the others.
I guess one advantage I could think of would be if you use these scripts on multiple pages, you only have to remember to include one script, and it saves some space.
At Google PageSpeed, they highly discourage you from using this technique, because it makes things slower. Apart from the sequential loading of your script.js before all the others, there's another catch:
Modern browsers use speculative parsers to more efficiently discover external resources [...] Thus, using JavaScript's document.write() to fetch external resources makes it impossible for the speculative parser to discover those resources, which can delay the download, parsing, and rendering of those resources.
It's also possible that this was written as a recommendation by an SEO firm to make the head element shorter if possible, so unique content is closer to the top of the document - also creating a higher text-to-HTML ratio. Though it does sound, all-in-all, like not a very good way of doing this; though it would make maintenance more time-consuming, a better approach would probably be to condense javascript into a single .js file and css into a single .css file, if it were deemed utterly necessary to reduce head element size.
A great disadvantage is that adding scripts into head will pause the processing of the document until those scripts were completely downloaded parsed and executed (because the browser thinks they may use document.write). - This will hurt responsiveness.
Now days it is recommended that you put your script tags right befo </body>. Of course this is not possible 100% of times, but if you are using unobtrusve Javascript (as you should), all scripts can be respositioned at the end of the document.
HTML5 came up with the async attribute which suggests the browser only to execute the scripts after the main document has been loaded. This is the behaviour of script-inserted scripts in many browsers, but notin all of them.
I advise against using document.write at all costs. Even without it, this results in one extra request towards the server. (We like to inimze the number of requests, for example with css sprites.)
And yes, as others mentioned earlier, if scriping is disabled your page will be shown without CSS (which makes it potentially unusable).
If JavaScript is disabled - <script> and <link> elements won't be added at all.
If you place JavaScript init functions at the bottom of your page (which is a good practice) and link CSS with JavaScript, it may cause a some delay before CSS loads (broken layout will be visible for a short time).

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