I have a every common page a.html which looks like this:
<html>
<head>
<script type="text/javascript" src="xyz.js" > </script>
</head>
<body>
<div> ... </div>
</body>
</html>
In b.html, I use jquery's .load() function to a div.
$("#myDiv").load("a.html")
It works. The xyz.js's content is loaded along with a.html. But why isn't there a <script> tag? I open firebug to see the source. There is a's but no a's <script>.
I want the <script> because I need it to find relative path.
(this question)
Edit: I tried to use .get() and .html(). Didn't help.
Edit2: The title is not very appropriate. The xyz.js runs. But no <script>.
The .load() function purposefully strips out <script> tags from the loaded content. When you give it a plain URL to load, it will execute the scripts after loading the content and adding it to the DOM. However, if you use the trick of adding a selector after the URL in the first argument:
$('#foo').load("http://some.domain.com/blah #special-div");
then it strips the <script> tags but it does not execute them.
Why? I don't know.
Now, please note that loading an entire page from the <html> tag on down into an element of another page is going to result in some sort of Frankenstein monster of a DOM, if a browser will do it at all. Generally, when you use ".load()" to grab fragments of content to update a page, your server should respond with a piece of a page, not the whole thing. The jQuery deal with allowing a selector after the actual URL is intended to let you strip out a chunk of a page, which is really cool, but it has that drawback that the scripts won't be executed in that case.
Because, it cannot run the script inside the <SCRIPT> tag. jQuery has .getScript() to call for scripts only. Check here
Related
I have a simple Javascript function that can be placed anywhere within HTML document. So I put it right below the closing , for example:
<html>
<body>
Some text.
<script>
document.getElementsByTagName('body')[0].innerHTML='hello';
</script>
</body>
</html>
My question is - would it make sense (from page load speed point of view) to load this script via the addEventListener("load") function instead? Ie. if I use this code below - which would be preferred? I understand that when Javascript is on the bottom of the page, it won't 'block' page rendering anyway, so using the addEventListener may only slow the execution down?
<html>
<body>
Some text.
<script>
window.addEventListener("load",function()
{document.getElementsByTagName('body')[0].innerHTML='hello';},
false);
</script>
</body>
</html>
Scripts should generally not be placed directly in the HTML like that, because they block further HTML parsing until they're executed. While it's not a problem if you have only one script, what if you have two, or three, or more, and some of them might take more than a handful of ms to parse?
Still, assuming that blocking isn't an issue, there's no real difference on way or the other, from the UX point of view.
Scripts, being information about how to interact with the content, but aren't actually content themselves, belong in the <head> IMO. If you don't like wrapping everything in a load listener, you can use the defer attribute to automatically run the script once the whole HTML has been parsed: <script src="..." defer>.
In HTML which was execute first head tag or body tag. I had this doubt while learing javascript and i need to include this file to the html so that.
It goes from top to bottom so the head executes first then the body, you can try it your self:
<head>
<title>test</title>
<script> alert('From Head'); </script>
</head>
<body>
<script>alert("From Body");</script>
</body>
Here is a codepen
It goes from top down, calling each script it finds while parsing the whole HTML document (normally the head tag goes first, with all the scripts inside, in the order they were placed). So if you need to include JS files, always put the least dependant ones at the top.
Also, if your JS scripts access DOM elements, make sure the script runs after the DOM is ready, by either using a window onload callback or placing the script before closing the body tag (so it comes "after" the DOM stuff).
I have read about several ways to embed Javascript in HTML document.
First, in head section:
<head>
...
<script src="abc.js"></script>
</head>
Second, in the end of document's body:
<body>
<!-- content -->
<script src="abc.js"></script>
</body>
First way is more esthetic, but second version assures that all the items in DOM are loaded. I use HTML5 (but probably it doesn't matter)
Which way is better and why?
if it is just a library of functions which aren't suppose to run when the page loads, you can safely put it in the head. Otherwise you need to wrap the code in abc.js with window.onload or $(document).ready(); and then embed it in the head
It depends on when you need the functionality in the script.
Before page load or else.
If it doesn't matter the second one in your example is better and more seciure since it allows the page content to load.
An error in the script may prevent for this to happen in before body case.
A lot depends on when you need script to execute if you need the page to be fully loaded or not. You can possibly put it in the head then execute a function with the onload event.
If you have JS code which is intended to run as part of loading/building the page, where in the HTML should this go? For instance modifying a <div> or adding some links.
Should this be put in the <body>, interspersed with HTML? Or should it be between the <head> and <body> elements? What order do things happen in - the order they are in the page or does HTML all happen before (non-<head>) JS is run?
If you have JS code which is intended to run as part of loading/building the page, where in the HTML should this go?
Just before the closing </body> tag is emerging as the best practice barring a specific requirement for it to be elsewhere (which there can sometimes be). It's the recommendation of the YUI folks, for instance, but it's not just them.
What order do things happen in - the order they are in the page or does HTML all happen before (non-) JS is run?
When a script tag is encountered, unless you use the defer or async attribute (and the browser supports them), all HTML parsing comes to a screeching halt and the script is downloaded and handed to the JavaScript interpreter. When the JavaScript interpreter finishes processing the script, the HTML parser can continue. It has to do this because the JavaScript can insert tokens into the HTML stream via document.write. This is also why you can load a script file and then load a second script file that relies on the first, and know that they'll get loaded in the right order. It's also why you can't access elements that are further down in the HTML stream from a script higher up in it unless you defer your code somehow (window.onload or the "DOM loaded" events many libraries support, such as jQuery's ready or Prototype's dom:loaded).
An upshot of this is that the typical practice of putting script tags in the head actually slows down the apparent load time of the page, unless those script tags need to be there for some reason. Hence the recommendation to put them just before the closing </body> tag.
There's a "gotcha" you have to watch for, though: If you have parts of the page that you want to respond to with JavaScript if the user has it enabled, loading your script at the very end leaves a brief but real race condition lying around: The user can interact with the page while your script is being downloaded. There are a variety of ways of handling that. My favorite is to detect whether JavaScript is enabled with inline script (not a separate file) in the head element and, if so, to put in a document-level handler for things where possible (you can do this with click events, for instance) which basically queues up or disables the click during that very brief period of time. That way, if JavaScript is enabled, you'll avoid the race condition, but if it isn't, any unobtrusive fallback you have in place will work.
The whole HTML file is executed in the order it is written, that means
<html>
<div id="ID"></div>
<script type="text/javascript">
document.getElementById('ID').innerHTML = "HELLO";
</script>
</html>
changes the contents of the div, wherease
<html>
<script type="text/javascript">
document.getElementById('ID').innerHTML = "HELLO";
</script>
<div id="ID"></div>
</html>
does not, because the JS code is executed before the div has loaded.
EDIT: If you want the JS to run after the page has loaded use window.onload or document.body.onload or
<body onload="...">
Alternatively if you're using a JS library such as jQuery, you can use
$(document).ready(function() {
...
});
Put them as functions in its own .js file which you include by <script src> at end of HTML <head> or <body>. If any of them needs to be executed during document load, call it using window.onload or whatever load function the JS library/framework offers, if you are using any.
As to the exact location, putting them in end of <head> allows them to be downloaded before the HTML page is been shown in browser and putting them in end of <body> allows the page to be shown a tad sooner because downloading the scripts will block the page rendering, thus it's a better speed experience.
However, IMO, it's a bit more robust to have the scripts downloaded before the page is rendered whenever you have some page elements which cannot be used without JS. In case of an impatient user this would otherwise lead to unusable elements.
I'd put it in a separate .js file and wrap the code so it is executed after the DOM is loaded. If you use a framework like jQuery or Prototype this should be easy.
For best performance place your JavaScript files at the BOTTOM of the HTML page you are serving.
To ensure that everything is set when you try to use it, execute only after the DOM is ready (there are multiple variations of this, my advice: Use a JavaScript Library).
You can put a script tag in the head, body, between the two, and more. You can put it most places but see this for a more in depth look.
I'm trying to dynamically insert the Tweetmeme button using Javascript. I'm currently using jQuery throughout the site. Here's the script that I'm using. I basically want to cycle through all the blog entries with a class of journal-entry and append the following JavaScript to the end. This Javascript comes straight from tweetmeme.com. This doesn't work for me though and it has something to do with the code between append(). It doesn't like the second set of script tags.
<script type="text/javascript">
$(document).ready(function() {
$('.journal-entry').each(function(index) {
$(this).append('<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script>');
});
});
</script>
Any help is appreciated.
Thanks.
Don't do this.
Inserting <script> HTML content into the DOM is unreliable: it works subtly differently in different browsers, and jQuery won't protect you from the differences.
In particularly, writing innerHTML never causes a <script> element's content to execute, but subsequently moving the <script> element from where it is to a new parent (which is part of jQuery's append process) may cause the script to execute, but not always (it depends on the browser).
In any case, it'll never work, because looking at button.js, it is calling document.write(). That function only makes sense to call at initial document parsing time; if you call it from an event afterwards, the call will simply replace the entire page content, destroying your existing page. A script that calls document.write() can only be run at document load time, from inside the execution path of a <script> element. You can't include the script in dynamically-created content at all, because it's not designed for it.
(If it makes you feel any better, it's barely designed at all; the button.js script is a badly broken load of old crap, including improper URL-escaping—using escape instead of the correct encodeURIComponent—and missing HTML-escaping. You may be better off well away from these total idiots.)
The closing </script> in the string in your append(...) call is closing the overall <script>
Try splitting it up into two strings. E.g:
$(this).append('<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></'+'script>');