What does the script tag do - javascript

Yo everyone. I am Admin's relative. Just a beginner in javascript. I would like to ask what is the following line, its purpose, what it does, where you put it and so on. My question might be simple but it would be really much appreciated if anyone can give good explanation to this question.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Thank you very much.

As you can see, this loading jQuery library from the CDN.
what is the following line
This will include jQuery library on your page
its purpose, what it does
As you might have read jQuery Tag WiKi on SO,
jQuery (Core) is a cross-browser JavaScript library (created by John Resig) which provides abstractions for common client-side tasks such as DOM traversal, DOM manipulation, event handling, animation and Ajax.
You might want to visit jQuery homepage.
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. If you're new to jQuery, we recommend that you check out the jQuery Learning Center.
where you put it
You can put this in head or at the end of body tag. You just need to add this before any jQuery plugin.
I'll highly recommend you to take this tutorial.

This line loads jQuery, a javascript library (see http://jquery.com for details on jQuery), in to your page. It is customary to put it in the <head> tag of your page, and as you're just beginning I would recommend that.
There are some cases, however, where you want to optimize your page load time and it may be better to put it at the end of the <bod> tag, right before </body>. But for now I'd put it in the <head>.
The src tells the script tag where to load the file from. In this case, it's from a CDN (content delivery network) which hosts the files, and is used for slightly faster download times (not something you'll need to worry about at this point).
And welcome to stackoverflow!

This line is usually placed in the header section of a webpage, but can always be placed anywhere depending on your need.
What the code does is it loads the javascript codes found at the link, onto the page.
This avoids having lengthy javascript codes within your webpage.

It is a link to an external script. It basically copies and pastes the code from that location into the file where you write it. You usually put it at the top of the file where you need it.

<script> tag is used for importing a script. (can be java script or vbscript.)
jQuery is a framework for JavaScript.
So the line you mentioned is to invoke the jQuery script code in your code.
Now, you can do it in two ways, either download it, and then give the src, or use it from cdn. The src in this line is from the CDN. For more details of how to use jQuery, the minimal you can read is: this.

It will load the content of the external script file. In this way you can better organise your code and reuse code libraries in different projects.
It is best practise to load the script files last in order for the browser to load the html first.

Related

jquery/javascript loading confusion

I'm using jquery and some ordinary javascript on my site and I've been told that I'd be better off loading all the javascript in a minimized form at the closing body tag of my pages rather than in the header as they are now.
I've also been told that I should clump all my JS together into one file to keep the number of requests down, although I've also been told there's some of my javascript which won't be able to be included in this mega file because it's needed by FB (for example).
So now I'm totally confused. For a start,
1) I use jquery and the jquery.ui, can these be lumped into the mega file and loaded at the end?
2) Can I just stick everything which currently appears in my page source surrounded by script tags into this file?
3) What must I leave out?
It's all a bit over-whelming when you're a learner
the site is at http://www.traditionalirishgifts.com/ as you can see I load:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
as well as a heap of other javascripts
As the comments point out, the answer depends on many variables.
Are you using any server side web framework? Any web framework worth it's money will offer you options for javascript and css concatenation. Typically these options allow you to define how exactly you want the concatenation to happen. Certain js files will change infrequently, example jquery, jquery ui. Whereas certain other files will change frequently, example your own application scripts. All these can be taken into consideration when deciding on what to concatenate.
If you could share which server side technology and what web server are you using, I can help you find specific solutions.
With regards to your three questions, its all about managing your dependencies. If your application scripts or "whatever currently appears in my page source surrounded by script tags" depend on jQuery or any other library, then they will need to included AFTER jquery or said library.
Dependency could also exist wrt the DOM. If your scripts output html directly using document.write then you will not be able to move them around easily.
I went through the html of the homepage of the site you linked to. The js code in that file can be moved to just before the end of the body, though you will need to ensure they appear in the same order. All the plugins you have included they seem to initialize themselves on document.ready which occurs only after all the html/js/css is parsed.
You are already referencing jquery/jqueryui from a CDN, so don't add them to the concatenated file.
I did not notice any code that you wouldn't be able to concatenate (on account of using FB). That said you could ask the person, who told you that, to explain why.
Finally, you can read more about optimizing front-end load times on YSlow (http://developer.yahoo.com/performance/rules.html) and Google Page Speed (https://developers.google.com/speed/docs/best-practices/rules_intro)
Personally, I would suggest you go ahead and move everything to just before the end of body. If something breaks, then ask questions on SO specific to the errors you receive.

Best practices for creating a reusable javascript web-app

I'm writing a web-app, using javascript, for the first time.
I was wondering what is the best method to make the web-app easily reusable, i.e. to make a "package" containing the js files, html and css, and load them like "load webapp"->launch it.
Currently I have an index.html which contains two divs:
the first one is a site-specific home page
the second one, initially hidden, is the panel of the web-app
once an initial selection is done in the homepage, I launch the app invoking a js method.
I'd like to make this more general, and I was wondering whether using jquery load() could be a clean solution (I'm currently using jquery). This would load the html, but I think I should still manually load the css in the page using the lib/app.
Any idea is appreciated.
Just make sure you don't embed any CSS or JS into your ASPX pages wherever possible, always keep them in separate files it'll be much easier to reuse certain aspects without having to dig around for the code. I've even seen JavaScript classes used to encapsulate a range of functionality, which could also be an option if you're that way inclined :).
In your said example, you're probably best calling a function in an external JS file on document ready.
Organizing your JS as JQuery plugins may also be an option for you. It may not make sense to put all of your JS into one plugin but if you split up your work into bite sized components this may make sense. Im not going to mention any particular resource because there are so many and I don't want to look like a spammer.
Hope this helps!
jQuery load won't help you organize your code, or load js dynamically, it has a complete other function (register to the onLoad event, or load an html page, or partial page via ajax)
If you're looking for dynamically load js libraries, use lab.js (at http://labjs.com) or require.js (at http://requirejs.org). But keep in mind that it can also be ok to have just one big js file that will get cached and load at once.
As far as organizing your js, it depends on the app. Sometimes jQuery plugin is the way to go. I had developed a solution that I am using on my projects, I just share it with you here: http://thebeast.heroku.com

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);
});

Where do you put your javascript?

Do you localize your javascript to the page, or have a master "application.js" or similar?
If it's the latter, what is the best practice to make sure your .js isn't executing on the wrong pages?
EDIT: by javascript I mean custom javascript you write as a developer, not js libraries. I can't imagine anyone would copy/paste the jQuery source into their page but you never know.
Putting all your js in one file can help performance (only one request versus several). And if you're using a content distribution network like Akamai it improves your cache hit ratio. Also, always throw inline js at the very bottom of the page (just above the body tag) because that is executed synchronously and can delay your page from rendering.
And yes, if one of the js files you are using is also hosted at google, make sure to use that one.
Here's my "guidelines". Note that none of these are formal, they just seem like the right thing to do.
All shared JS code lives in the SITE/javascripts directory, but it's loaded in 'tiers'
For site-wide stuff (like jquery, or my site wide application.js), the site wide layout (this would be a master page in ASP.net) includes the file. The script tags go at the top of the page.
There's also 'region-wide' stuff (eg: js code which is only needed in the admin section of the site). These regions either have a common layout (which can then include the script tags) or will render a common partial, and that partial can include the script tags)
For less-shared stuff (say my library that's only needed in a few places) then I put a script tag in those HTML pages individually. The script tags go at the top of the page.
For stuff that's only relevant to the single page, I just write inline javascript. I try to keep it as close to it's "target" as possible. For example, if I have some onclick js for a button, the script tag will go below the button.
For inline JS that doesn't have a target (eg: onload events) it goes at the bottom of the page.
So, how does something get into a localised library, or a site-wide library?.
The first time you need it, write it inline
The next time you need it, pull the inline code up to a localised library
If you're referencing some code in a localized library from (approximately) 3 or more places, pull the code up to a region-wide library
If it's needed from more than one region, pull it up to a site-wide library.
A common complaint about a system such as this, is that you wind up with 10 or 20 small JS files, where 2 or 3 large JS files will perform better from a networking point of view.
However, both rails and ASP.NET have features which handle combining and caching multiple JS files into one or more 'super' js files for production situations.
I'd recommend using features like this rather than compromising the quality/readability of the actual source code.
Yahoo!'s Exceptional Performance Team has some great performance suggestions for JavaScript. Steve Souders used to be on that team (he's now at Google) and he's written some interesting tools that can help you decide where to put JavaScript.
I try to avoid putting javascript functions on the rendered page. In general, I have an application.js (or root.js) that has generic functionality like menu manipulation. If a given page has specific javascript functionality, I'll create a .js file to handle that code and mimic the dir structure on how to get to that file (also using the same name as the rendered file).
In other words, if the rendered page is in public/dir1/dir2/mypage.html, the js file would be in public/js/dir1/dir2/mypage.js. I've found this style works well for me, especially when doing templating on a site. I build the template engine to "autoload" my resources (css and js) by taking the request path and doing some checking for the css and js equivalents in the css and js directories on the root.
Personally, I try to include several Javascript files, sorted by module (like YUI does). But once in a while, when I'm writing essentially a one-liner, I'll put it on the page.
Best practice is probably to put it on Google's servers.
(Depends what you mean by "your" javascript though I suppose :)
This is something I've been wrestling with, too. I've ended up by using my back-end PHP script to intelligently build a list of required JS files based on the content requested by the user.
By organizing my JS files into a repository that contains multiple files organized by purpose (be they general use, focused for a single page, single section, etc) I can use the chain of events that builds the page on the back-end to selectively choose which JS files get included based on need (see example below).
This is after implementing my web app without giving this aspect of the code enough thought. Now, I should also add that the javascript I use enhances but does not form the foundation of my site. If you're using something like SproutCore or Ext I imagine the solution would be somewhat different.
Here's an example for a PHP-driven website:
If your site is divided into sections and one of those sections is calendar. The user navigates to "index.phhp?module=calendar&action=view". If the PHP code is class-based the routing algorithm instantiates the CalendarModule class which is based on 'Module' and has a virtual method 'getJavascript'. This will return those javascript classes that are required to perform the action 'view' on the 'calendar' module. It can also take into account any other special requirements and return js files for those as well. The rendering code can verify that there are no duplicates of js files when the javascript include list is built for the final page. So the getJavascript method returns an array like this
return array('prototype.js','mycalendar.js');
Note that this, or some form of this, is not a new idea. But it took me some time to think it important enough to go to the trouble.
If it's only a few hundred bytes or less, and doesn't need to be used anywhere else, I would probably inline it. The network overhead for another http request will likely outweigh any performance gains that you get by pulling it out of the page.
If it needs to be used in a few places, I would put the function(s) into a common external file, and call it from an inline script as needed.
If you are targeting an iphone, try to keep anything that you want cached under 25k.
No hard and fast rules really, every approach has pros and cons, would strongly recommend you check out the articles that can be found on yahoo's developer section, so you can make informed decisions on a case by case basis.

Categories