Javascript - inline vs external script - what's the difference? - 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

Many partial javascript sections

Does many javascript sections on different places affect page loading time?
like
<html><script></script><body><script></script></body><script></script></html>
Also is there any affects while using referces or writing small script parts on html?
And last, is it bad or good to write many codes on document load in page, will it affect page laod time while compiling all scripts on load
Obviously loading many different external JavaScript files will increase final load time.
You can place all the <script> tags at the end of your document, right before the </body> so that the website loads before the scripts. If possible you could minify and combine your JS files, to decrease the number of HTTP requests as well.
Page rendering will start as soon as all CSS is loaded and the DOM has been parsed, so this will make it seem like it loads faster.
Try following some recommendations, like the Best Practices for Speeding Up Your Web Site, if you are concerned about page speed.
Having JavaScript snippets inline with your HTML would not be a good idea. Try to keep your HTML clean, and use JavaScript with the appropriate selectors if you want to alter the DOM adding or removing any element.
The best practice requires you to load or run javascript at the bottom of the page(footer).
This way all the assets of the page (html, css, images) are loaded first.
Then load and execute javascript code.
Regarding speed the best way is to put all your js code to one .js file (if possible) and minimize it.
This way you can cut loading time and http requests giving a speed boost to your site.

HTML5 Boilerplate Page-specific Javascript Placement

Question
If you use a single javascript file to hold all scripts, where do you put scripts that are for just one page?
Background
This may be a matter of opinion or "best practice" but I'm interested in others' opinions:
I'm using the html5 Boilerplate on a project. They recommend you place all javascript in a single file script.js for speed and consistency. Seems reasonable.
However, I have a bit of geolocation script that's only relevant to a single page, and not others. Should I break convention and just put this script on the page below my calls to the javascript libraries it depends on? Just put calls to the relevant functions (located in the script.js) file, below the links to the libraries they depend on?
Thanks!
The good folks at html5 boilerplate recommend putting all of your javascript in script.js so that the browser will only have to load that one file (along with the others that h5bp uses) and to allow caching of that file.
The idea is not to get caught up in the "recommended" way, and to think about things related to your own applications.
This geolocation file is only going to be used on this one page, right? It will never be used anywhere else.
The script.js file will be used on multiple pages.
Well, then it wouldn't make sense to put a "whole script" that will only be needed on one page in the script.js file. You should make the file external and call it separately on the page that it is needed. This will keep you from bloating the script.js file for functionality that may never get used by that user.
However, if your "whole script" for the geolocation functionality is pretty small, then include it in script.js. If it doesn't add to the speed of the download for that file, then it makes sense to include it there.
The gist of all of this is, What is the best trade off for my application?
These things we know to be true:
cached js files are good
fewer files to download are good
smaller files to download are good
maintenance is important
Once you think of these things in terms of your application, the decision making becomes a bit easier. And remember, decisions that trade off milliseconds are not going to make much of a difference in your user's "perception" of how fast your page is.
The browser will only download the .js files once (unless something is happening to discourage the browser from caching). So if you expect all of your users to hit the one page that uses geolocation sometime during their session, then you might as well give it to them early. If you expect maybe a tiny percent of your users to eventually hit the geolocation page, then maybe you might want to split them.
Split it out into a separate .js file so that it can be cached. Then reference both external .js files from your page.
I think you should put it in a separate file. Putting all the scripts in one single file could cause unexpected behavior and conflicts. I like to have one script file for the javascript that all pages will use containing plugins, helper functions, formatting functions etc. And then create one separate js file for everything that is relevant just for each page.
If you still want to have just one js file in the browser you could take advantage of one of those utilities that combine multiple js files into one.

What are the best practices for loading javascript with the least amount of impact on display performance of the page?

Is there a way to download javascript without executing it? I want to decrease my page load times so am trying to "lazy load" as much javascript onto the page while the user is idle. However I don't want the javascript to execute, I just want it to be in the browser cache.
Should I use an object tag? I noticed that I can use a LINK tag but that makes the browser think it's css which has a negative impact on my ui perf / responsiveness.
As long as you have all code in functions or classes and nothing in global scope nothing will execute.
You can then start your script with a call from
window.load(function() { //your initialisation here });
This will let the whole page load before running any scripts.
You could also add script references via script to make sure they load after any images in the page.
Just add a script element to head using script and it will load.
These pages has examples for this:
http://unixpapa.com/js/dyna.html
http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
This way if you have a slow connection or a sever that is overloaded, the visible elements will be loaded first by the browser.
As far as I know, there is no cross-browser compliant way to get around JavaScript loading in serial. If your javascript does something when it is loaded, you need to refactor your code. For instance, you don't write your jQuery commands/actions/code in the jQuery library script; you link the jQuery library and then put your jQuery commands into a separate file. You should do the same thing with your custom libraries. If this isn't possible, you have a big problem with the architecture of your code.
Also, make sure you stick non-executing JS at the bottom of the page near the </body> tag. This will allow everything else to load first, so that the bulky JS libraries don't slow down things like CSS and images.
The best practices way to deal with external javascript is to have it load after everything else on the page by putting it at the bottom of the page. Then everything that can be rendered will be and display and then the javascript at the bottom of the page will load and be compiled and cached. Of course this only works if the javascipt is a library of functions that don't need to be executed mid-page, in that case, you are stuck with serial javascript loading compiling and execution regardless.
Require.JS is a great library for automatically managing when your javascript loads.
You could load the file using the XMLHttpRequest object in JavaScript. (Aka AJAX). (end then of course just discard the result ^^).

Where should JavaScript be put?

I've been doing a little JavaScript (well, more like jQuery) for a while now and one thing I've always been confused about is where I should put my scripts, in the <head> tag or in the <body> tag.
If anyone could clarify this issue, that'd be great. An example of what should go where would be perfect.
Best practices from google and yahoo say that, for performance, javascript should always be put in an external file, and linked to your page with a <script> tag located at the bottom of the html, just before the closing of the <body> element.
This allows the browser to render the entire page right away, instead of stopping to evaluate javascript.
You mentioned three places:
In tags;
In the HTML; and
In an external file.
Let me address each of those.
Best practice is to have common Javascript in one or more external files and the less files the better since each JS file loaded will block loading of the page until that JS file is loaded.
The word "common" is extremely important. What that means is you don't want to put page-specific Javascript code in that external file for caching reasons. Let's say you have a site with 1000 pages. Each page has JS code specific to it. That could either be 1000 different files or one really big file that executes a lot of unnecessary code (eg looking for IDs that aren't on that particular page but are on one of the 999 others). Neither of these outcomes is good.
The first gives you little caching boost. The second can have horrific page load times.
So what you do is put all common functions in one JS file where that JS file only contains functions. In each HTML page you call the JS functions needed for that page.
Ideally your JS files are cached effectively too. Best practice is to use a far futures HTTP Expires header and a version number so the JS file is only loaded once by each browser no matter how many pages they visit. When you change the file you change the version number and it forces a reload. Using mtime (last modified time of the JS file) is a common scheme, giving URLs like:
<script type="text/javascript" src="/js/script.js?1233454455"></script>
where that mtime is automatically generated. Your Web server is configured to serve JS files with an appropriate Expires header.
So that mixes external files and in-page scripts in (imho) the best way possible.
The last place you mentioned was in the tag. Here it depends somewhat on what JS libraries and frameworks you use. I'm a huge fan of jQuery, which encourages unobtrusive Javascript. That means you (hopefully) don't put any Javascript in your markup at all. So instead of:
do stuff
you do:
do stuff
with Javascript:
$(function() {
$("#dostuff").click(doStuff);
});

Speed up web site loading

I am looking for the best way to speed up the load time of my js.
The problem is that I am working with a very large site that uses the jquery framework, and what's happening is because the site is also loading, facebook connect, addthis sharing, google analytics and another tracking code, the jquery is delayed a few seconds, and certain elements like the calendar just appear, and my users are complaining that things take to long.
I did a test in google chrome and the avg load time is 4s. Which is too much.
I am already doing minification, and the jquery UI/ Jquery is being loaded from google. What's the best way to approach this?
Make fewer http calls by combining images and script and css, and also use a Content Delivery Network for you static images and css might help!
You are not likely to be able to do much more about the load time of the external scripts, so what you can do is to change the order that things happen in the page so that the external scripts are loaded after you have initialised the page.
Scripts are loaded and executed in a serial manner, so if you change their order in the source code, you also change the order they are loaded.
Instead of using the ready event in jQuery, you can put your initialising code inline in the page, after all the content but before the body closing tag. That way the elements that you want to access are loaded when the script runs, and you can put external scripts below the initialising code to make them load after.
Small technical changes (such as serving the JSs from Google, minifying, etc..) will only get you so far.
Seems you simply have lots of dynamic stuff going on in your page. Have you though of an asynchronous way of building your content? One option might be to place placeholders instead of the external content, and asynchronously load it, so when all the scripts are loaded and ready, all you need to do is throw the markup into the placeholder.
This will create a better user experience, instead of the user waiting 10 seconds for the entire page, it will start loading incrementally after 2 seconds (and still fully load after 10).
In addition to Yuval's answer some options that might or might not bring you a speed gain:
the load time of external libraries is something beyond your control. Try to include them as late as possible, and better still, dynamically after the page has loaded. This way your page won't stall, if Google analytics or Facebook have another hickup.
It is not necessarily faster to load jQuery from Google. Consider putting jQuery, jQuery UI and as many of your own JS as reasonable in a single file, minify and gzip it and let the server serve the gzipped version where possible. Note here, that the gain in speed depends largely on what your users cache and where they cache it. If they already have jQuery from Google in their cache, this technique might make page load slower.
The bottomline is, that after some optimization you're out for experimenting. You must find out, what your average user has in her cache, if the page is accessed directly via deep links or if you can smuggle some JS or CSS (or even images) into her cache via a previous "landing page".
Make sure you deliver your content in gzip/deflate encrypted format. Combine multiple javascript files into 1 file, which helps to reduce the number of http requests.
P.S. Here's a test tool to check if compression is configured:
http://www.gidnetwork.com/tools/gzip-test.php

Categories