javascript in the <body> - javascript

I used to believe that you should not insert javascript blocks
<script language="javascript">
<!--
//-->
</script>
into the body part of a (what, HTML, XHTML?) document, but rather into the head.
But is that still true?

Script in the body (not links to external files) is like putting CSS in the head--people move toward separating it so that they can have the markup and logic separate for clarity and ease of maintenance.
I'm a big fan of the document ready feature of Jquery...but that's just personal preference. A dom loader is really the only way to guarantee loading is going to be identical between the various different browsers. Thanks, Microsoft!
I say use common sense...it's not worth doing another file for a single line of code...or even two. If we all went to the extremes that best practices sometimes ask us to go, we'd all be nuts.....or at least more nuts than we are now.

But is that still true?
I'm not sure it ever was. Are you thinking about <style> CSS elements? Because those are illegal in the body.
But it is usually the better choice to put Javascript code into the head or a separate script, and wrap it in a document.ready or onload event.
However, in-body Javascript can have its place, for example when embedding external JavaScripts that document.write() stuff into the document. Top-modern, bleeding-edge Google Analytics relies on a <script> segment being inserted into the very end of the body.

But is that still true?
It is a matter of good/best practices. HTML and Javascript should be separate. This is even knows as unobtrusive javascript/code.
More info at wikipedia:
Unobtrusive JavaScript
Although this is a good practice, but you can still put javascript at any part of the page, however you should avoid this as much as possible.
Some advocate that javascript should only go at the end of the page, for example they seem to say that is is better in terms of SEO (Search Engine Optimization) as well as performance as denoted by #David Dorward in his comment.

According to Yahoo, for the best performance it's recommended to put any script tags at the end of your document just before the closing html tags:
http://developer.yahoo.com/performance/rules.html
Google suggests using a deferred method to load scripts:
http://code.google.com/speed/page-speed/docs/payload.html#DeferLoadingJS
But they should almost always be script calls to an external .js file. There are very few occasions where it's better to have the .js embedded on the page.

It's not recommended because if you try to access elements in the body itself (i.e forms, fields, etc) since they may only become available once the entire body has rendered. However, it's a valid and actually very common practice.

Related

What type of magic is LinkedIn doing with their JS SDK? script body and src are present, plus body in weird format

I want to integrate LinkedIn sharing on my page.
Reading the documentation that LinkedIn provides here:
https://developer.linkedin.com/docs/getting-started-js-sdk
.. I was surprised to see they require this script tag in the head secion of my page
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: [API_KEY]
onLoad: [ONLOAD]
authorize: [AUTHORIZE]
lang: [LANG_LOCALE]
</script>
I don't get what is happening here. First of all, w3schools says that """Note: If the "src" attribute is present, the element must be empty.""" (https://www.w3schools.com/tags/tag_script.asp).
I also went here: https://html.spec.whatwg.org/multipage/scripting.html#the-script-element
(I'm not 100% sure how authoritative this is...but looks authoritative based on the format and length :P) - it also says there that if there's a src attribute, then the body should basically be empty - in any case - LinkedIn's script syntax is not explainable by these 2 resources.
So does anyone know what's up with the script body syntax? Are those JS labels? And if so, I don't get how they're used. I thought labels are used with continue/break statements, to get out of loops. I don't understand how LinkedIn's API can get information from me if I provide it in that syntax.
Is the script body somehow fed to the script, and it parses it itself?
Can someone please explain to me what's going on?
Thanks!
What you said is correct. When the src attribute is added, the body of the script is not executed. There is a way to get around this however. That's by retrieving the script tag, extracting the innerHTML and using eval on it. You will need to of course do that on document ready.
I don't know how LinkedIn does it exactly, but HTML standards didn't change for them nor the order of loading, so either they use something similar to what I explained or some more clever way of parsing the body of the script.
Other notes to consider: instead of using document ready event, you could bind that into your library. As in retrieve the last available script tag, and extract the body, at the time of load of your library, that will be the last element loaded either way, so you should be able to retrieve the code without using any events. (That would need testing, but DOM elements are loaded synchronously, top-down approach).
Obviously using eval is not recommended, its quite slow, but definitely provides the functionality you're looking for.
PS. Forgive any formatting errors. I'm typing this from my mobile, 2k miles away from home. Otherwise I'd be more than happy to even provide some sample code snippets and do the above testing myself.

Running Javascript from external file loaded with AJAX

I've been trying to get this sorted all day, but really cant figure it out. I've got a page with <div id="ajax"></div> that is populated off a tab based menu pulling in a snippet of HTML code stored in an external file that contains some javascript (mainly form validation).
I've seen in places that I need to eval() the code, but then on the same side of things people say its the last thing to do.
Can someone point me in the right direction, and provide an example if possible as I am very new to jQuery / JavaScript.
Many thanks :)
pulling in a snippet of HTML code stored in an external file that contains some javascript (mainly form validation).
Avoid doing this. Writing <script> to innerHTML doesn't cause the script to get executed... though moving the element afterwards can cause it to get executed, at different times in different browsers.
So it's inconsistent in practice, and it doesn't really make any sense to include script anyway:
when you load the same snippet twice, you'd be running the same script twice, which might redefine some of the functions or variables bound to the page, which can leave you in extremely strange and hard-to-debug situations
non-async/defer scripts are expecting to run at parse time, and may include techniques which can't work when inserted into an existing document (in the case of document.write this typically destroys the whole page, a common symptom when trying to load third-party ad/tracking scripts).
Yes, jQuery tries to make some of this more consistent between browsers by extracting script elements and executing them. But no, it doesn't manage to fix all cases (and in principle can't). So don't ask it to. Keep your scripts static, and run any binding script code that needs to happen in the load callback.
If you fetch html via Ajax, and that html has a <script> tag in it, and you write that html into your document via something like $('#foo').append(html), then the JS should run immediately without any hassle whatsoever.
jquery automatically processes scripts received in an ajax request when adding the content to your page. If you are having a particular problem then post some code.
See this link
dataType: "html" - Returns HTML as
plain text; included script tags are
evaluated when inserted in the DOM.

How do you re-use javascript functions

We have lots of javascript functions, which are usually handled via the onclick function. Currently they are present in every file where-ever it is needed. Would it make sense to consolidate all javascript functions into a single file and use this where-ever it is needed? What is the general practice here
<s:link view="/User.xhtml"
onclick="if (confirm('#{messages['label.user.warning']}')) {
var f = $('user');
f.method = 'POST';
f.action = f.submit();
} return false;">
Yes! Absolutely factor this out into an external javascript. Imagine if you needed to change something in this code. How many places do you have to change now? Don't duplicate code. It must makes your page bigger, which obviously affects how much is getting downloaded.
It's up to you to determine where the reusability lies in your own code. But it's easy enough (and a good idea) to create a library of often-used functions. Create a file like mylib.js, for instance, with things like...
function saveUser(f)
{
//...
f.method = 'POST';
f.action = f.submit();
}
add this to your pages:
<script type="text/javascript" src="mylib.js"></script>
add code your events like this:
<s:link view="/User.xhtml" onclick="return saveUser($('user'));">
Notice that the library code avoids any dependencies on the layout or naming of elements on the pages that use it. You may also want to leave little comments that will remind your future self what the purpose and assumptions of these library functions are.
Would it make sense to consolidate all javascript functions into a single file and use this where-ever it is needed?
Ummm...yeah
It would be better to do something like this:
function saveUser() {
// logic goes here
}
and use the markup
<s:link view="..." onclick="saveUser();">
Using code inline like that is very bad. Don't do it. Or the prorgamming gods will grow restless.
It is always a good idea to put JavaScript code in JavaScript files. Like you don't mix content and presentation (XHTML and CSS), you don't have to mix content and interactivity (XHTML and JavaScript).
Putting JavaScript code in a separate file has several advantages:
No need to duplicate code (so better reuse),
Possibility to minify the source code, thing which is quite impossible to do if you put together XHTML and JavaScript,
Ability to use non-intrusive JavaScript, helping to create more accessible websites (there is probably nothing wrong from the accessibility point to use onclick and other events, but it becomes very easy to forget that the website must work without JavaScript, thus developing a non-accessible website).
Better client-side performance: larger pages make things slower; when you put JavaScript outside, the pages are smaller, and the .js file is cached by the browser instead of being loaded on every request.
Javascript can be accessed via a script tag, which can point to an external script or define it for use in this document only.
<script type="text/javascript" src="mycustom.js"></script>
<!-- OR -->
<script type="text/javascript">
function saveUser(username) {
//code
}
</script>
No offense, but if you didn't know that you are either very new at this or you skipped a lot of steps in learning javascript. I recommend going through the w3schools.com tutorial on javascript and anything else you'll be using.

Is it right to write multiple and separate <script > on a page?

While writing JavaScript code, I Separate each code block with <script> tags
<script type="text/javascript">
//---- code block 1---------
</script>
<script type="text/javascript">
----code block 2-----
</script>
<script type="text/javascript">
$(document).ready.(function(){
// code block3
});
</script>
I want to know that is it good practice to write separate <script type="text/javascript"></script> on the same page
--or--
We have to write all JavaScript code under one <script>
What are the technical differences in each way?
Well, you may want to ask yourself why your code organization scheme leads to that setup, and whether it causes maintenance or understandability problems, but I don't think it's strictly "bad". Now if your <script> tags are actually fetching separate files from the server, then it's a good idea to cut back on them.
The browser parses and interprets script tags in such a way that other work stops, so blocks of Javascript up at the top of your page can slow things down if they do a lot of work. That's true whether you've got a big block of code or several smaller blocks, however.
An advantage of moving to separate script files is that you can re-use code on multiple pages. When you do that, it may be easier at build time to compress your scripts with YUICompressor or some other similar tool.
The best reason to do this is if each script represents a discrete chunk of functionality which may not be used on (and therefore not vended to) every page. In that case, it becomes a smart strategy.
Having multiple <script> tags makes no real difference in performance but is less readable.
There is one edge case where multiple script blocks can make a difference (and I just learned about it). If one line of code references a value before it has been declared, this will work if the code belongs to the same script block, but not if they are separate. But this doesn't change the answer everybody gave you: it probably won't matter in everyday coding.
You don't have to, but its obviously cleaner that way, unless you want to clearly seperate the blocks of code.
Put all your javascript coding in separate and then call the file name. Because it is good thing. Coding execution is step by step, so it will take time if js present in between the coding.
Not nice, but not a problem.
Hunter is right, it makes absolutely no difference as far as performance is concerned.
When your javascript however becomes more complex, you may want to start building your own API of sorts and splitting out all of those tags into separate files. Then when you're deploying your app, find some sort of packaging solution that will combine all of those files to a single one, compress it using YUI compressor or Google Closure and have one single tag that references this file of all your code.
While it is a 'slight' disadvantage to force a separate http request for this file, if it's packaged properly, the file size will be smaller than the uncompressed code you've included in that file.
It is also normal to have script tags further down in your page that provide extra functionality (ie look at google analytics)
Whenever you are violating the DRY principle (Don't Repeat Yourself), you need to ask why. If you don't have a good reason, then you probably shouldn't be doing it that way.

Where to put JavaScript configuration functions?

What is the general developer opinion on including javascript code on the file instead of including it on the script tag.
So we all agree that jquery needs to be included with a script file, like below:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"
type="text/javascript"></script>
My question is, in order to get functions on a page that is not on all pages of a site. Do we include the functions like below in the same page or in a global include file like above called mysite.js.
$(document).ready(function(){
$(".clickme").click(function(event){
alert("Thanks for visiting!");
});
});
ok. So the question is: if the code above is going to be called in every class="clickme" on a specific pages, and you have the ability to call it either from an include separate file called mysite.js or in the content of the page. Which way will you go?
Arguments are:
If you include it on the page you will only call it from those specific pages that the js functionality is needed.
Or you include it as a file, which the browser cached, but then jquery will have to spend x ms to know that that function is not trigger on a page without "clickme" class in it.
EDIT 1:
Ok. One point that I want to make sure people address is what is the effect of having the document.ready function called things that does not exist in the page, will that trigger any type of delay on the browser? Is that a significant impact?
First of all - $("#clickme") will find the id="clickme" not class="clickme". You'd want $(".clickme") if you were looking for classes.
I (try to) never put any actual JavaScript code inside my XHTML documents, unless I'm working on testing something on a page quickly. I always link to an external JS file to load the functionality I want. Browsers without JS (like web crawlers) will not load these files, and it makes your code look much cleaner to the "view source".
If I need a bit of functionality only on one page - it sometimes gets its own include file. It all depends on how much functionality / slow selectors it uses. Just because you put your JS in an external JS file doesn't mean you need to include it on every page.
The main reason I use this practice - if I need to change some JavaScript code, it will all be in the same place, and change site wide.
As far as the question about performance goes- Some selectors take a lot of time, but most of them (especially those that deal with ID) are very quick. Searching for a selector that doesn't exist is a waste of time, but when you put that up against the wasted time of a second script HTTP request (which blocks the DOM from being ready btw), searching for an empty selector will generally win as being the lesser of the two evils. jQuery 1.3 Performace Notes and SlickSpeed will hopefully help you decide on how many MS you really are losing to searching for a class.
I tend to use an external file so if a change is needed it is done in one place for all pages, rather than x changes on x pages.
Also if you leave the project and someone else has to take over, it can be a massive pain to dig around the project trying to find some inline js.
My personal preference is
completely global functions, plugins and utilities - in a separate JavaScript file and referenced in each page (much like the jQuery file)
specific page functionality - in a separate JavaScript file and only referenced in the page it is needed for
Remember that you can also minify and gzip the files too.
I'm a firm believer of Unobtrusive JavaScript and therefore try to avoid having any JavaScript code in with the markup, even if the JavaScript is in it's own script block.
I agreed to never have code in your HTML page. In ASP.net I programmatically have added a check for each page to see if it has a same name javascript file.
Eg. MyPage.aspx will look for a MyPage.aspx.js
For my MVC master page I have this code to add a javascript link:
// Add Each page's javascript file
if (Page.ViewContext.View is WebFormView)
{
WebFormView view = Page.ViewContext.View as WebFormView;
string shortUrl = view.ViewPath + ".js";
if (File.Exists(Server.MapPath(shortUrl)))
{
_clientScriptIncludes["PageJavascript"] = Page.ResolveUrl(shortUrl);
}
}
This works well because:
It is automagically included in my files
The .js file lives alongside the page itself
Sorry if this doesn't apply to your language/coding style.

Categories

Resources