when and where to put javascript in html - javascript

I am new to Java script. I am practicing code.When i put my code in the head section, then i get element null, and when i put it inside body, but before element, then i also get null, but if i put it inside body, but after element then i get the element. I want to ask why i am getting null in case of the first two cases. Here is my code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/attributes.js"></script> // null
</head>
<body>
<script type="text/javascript" src="js/attributes.js"></script> // null
<a id="braingialink"
onclick="return showAttributes();"
href="http://www.braingia.org" >Steve Suehring's Web Site
</a>
<script type="text/javascript" src="js/attributes.js"></script> // ok
</body>
Here is my javascript
var a1 = document.getElementById("braingialink"); //get null in first two cases
window.alert(a1.getAttribute("href"));
a1.setAttribute("href", "www.google.com");
window.alert(a1.getAttribute("href"));
function showAttributes() {
var e = document.getElementById("braingialink");
var elementList = "";
for (var element in e) {
/**
* Sometimes, especially when first programming with JavaScript, you might not know what
* attributes are available for a given element. But you don’t have to worry about that, because
* of a loop that calls the getAttribute() method.
*/
var attrib = e.getAttribute(element);
elementList = elementList + element + ": " + attrib + "\n";
} //end of for()
alert(elementList);
} //end of function showAttributes
And also tell me, placing <script type="text/javascript" src="js/attributes.js"></script>
after the a element, is the same as i write script in the script tag , like
Steve Suehring's Web Site
<script type="text/javascript">
var a1 = document.getElementById("braingialink");
alert(a1.getAttribute("href"));
a1.setAttribute("href","http://www.microsoft.com");
alert(a1.getAttribute("href"));
</script>
Are both things mean to same?
Thanks

The browser parses the document from top to bottom, and if it encounters a <script> block (whether inline script or inclusion of an external JS file) it runs that JavaScript before parsing any more of the document. If that particular code block tries to refer to any elements it can only access the ones above it in the source, i.e., the ones already parsed.
The document.getElementById() method returns null if no element is found for the id you supply, so if you try to use it to access elements below it in the source they've not yet been parsed and can't be found.
The two most common practices to deal with this are:
Put all of your script at the bottom of the <body> such that when it runs all of the elements will have been parsed.
Create an "onload" handler, that is, define a function that will be run as soon as the document finishes loading. You can do this from a script block in the <head> - the JavaScript that defines the onload function is run immediately, but then the function is executed later after everything has loaded.
Following is the simplest way to do option 2:
window.onload = function() {
var x = document.getElementById("x");
// other element manipulation here
};
There is nothing stopping you doing 1 and 2 in the same document, along with throwing some <script> blocks in the middle of the document, but most people find it neater to keep all their code in the one spot.

You're getting null in the head because the DOM has not loaded - your objects are nonexistent at that time. Use this:
window.onload = function () {
// Your code
}
Oh and also take a look at the .ready() function of jQuery here. It would certainly help the headache later on.

Normally you should put script blocks inside the head tag. You can put them in the body tag if you have a special reason, for example to make the script load later because it comes from a slow server.
The reason that you can't access the element, is that the code runs before the browser has parsed the code for the element, so the element simply doesn't exist yet.
You use the load event to run the code after the document is loaded:
window.onload = function() {
// here you put the code that needs to access the elements
}

see http://www.w3schools.com/js/ and http://www.w3schools.com/js/js_whereto.asp
You can place an unlimited number of scripts in your document, and you can have scripts in both the body and the head section at the same time.
It is a common practice to put all functions in the head section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.

You need to understand how web browsers load resources into a page. Firefox -> Firebug add-on Net tab shows the timeline of how resources are loaded. If you are using jQuery or something like it (and you aught to) - then stick your code inside $(document).ready(function() { .. } - that will ensure the page has fully loaded.
Also, it's a good practise to to include your custom js last thing before </body> tag - that way page DOM would have loaded.
Have a read if you want to understand this deeper:
http://www.goodreads.com/book/show/6438581-even-faster-web-sites
and
http://www.goodreads.com/book/show/1681559.High_Performance_Web_Sites

Best would be right before the closing body tag, to not disturb the page loading and rendering at all! It's also recommended by google, for example for analytics snippet and also by facebook!

you get nulls because your script executes while the browser is still loading the page. Since the page might not yet have all elements rendered, you get nulls. you need to run the script when the page has finished loading.
put your script in to the HEAD element, and invoke it on body's onload event.

Related

Javascript adding <script> tag after page loads

Got a little problem here. Basically, I'm trying to add a script tag after the page loads.
This is what I am doing:
index.php:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function getad()
{
$.post('assets/getad.php', "ad", function(response) {
response = response.replace('document.write','document.getElementById("ad").innerHTML = ');
eval(response);
console.log(response);
});
}
getad();
</script>
<div id="ad"></div>
</body>
</html>
getad.php:
<?php
echo file_get_contents("http://ads1.qadabra.com/t?id=a823aca3-9e3c-4ddd-a0cc-14b497cad85b&size=300x250");
?>
You can find a demo here: http://dev.cj.gy/game/
As you can see, the #ad div DOES get filled with the correct script tag, but it doesnt actually run, If I edit the page to include the script tag right at page load, it does run.
Yes, <script> tags cause execution when parsed as part of the main document; they don't execute from being written to innerHTML.
You can create an executing script element outside of that initial parse using the DOM method of calling createElement('script'), setting its src/content and adding it to the document. This is what jQuery's getScript does.
However it wouldn't do you much good because the next script, that ads1.qadabra.com is document.writeing to the page, also itself calls document.write.
You could work your way around both of these calls at the client side (ie without getad.php), by assigning your own custom function to document.write that, instead of writing to the loading page, attempts to extract the source of the script tag passed to it, and load that in a DOM-created script element.
But in general these are scripts designed to work synchronously at document load time; anything you do to try to force them to run in a way they weren't intended to is likely to be fragile and stop working when the ad network change anything.
If you want to load a third-party ad without pausing the loading of the parent document, I suggest putting it in an iframe.

Div is not created before javascript run

I have a question about javascript/html.
First, I have this:
var post = document.body.getElementsByClassName("post");
var x=post[i].getElementsByClassName("MyDiv")[0].innerHTML;
I get from the debugger that x is not defined, it doesn't exists.
This javascript function runs onload of the body. I am sure that I gave the right classnames in my javascript, so it should find my div.
So, I read somewhere that sometimes javascript does not find an element because it is not yet there, it is not yet created in the browser ( whatever that means).
Is it possible that my function can't find the div with that classname because of this reason?
Is there a solution?
So, I read somewhere that sometimes javascript does not find an element because it is not yet there, it is not yet created in the browser ( whatever that means).
Browsers create the DOM progressively as they get the markup. When a script element is encountered, all processing of the markup stops (except where defer and async have an effect) while the script is run. If the script attempts to access an element that hasn't been created yet (probably because its markup hasn't been processed yet) then it won't be found.
This javascript function runs onload of the body.
If that means you are using something like:
<body onload="someFn()"...>
or perhaps
<script>
window.onload = function() {
someFn();
...
}
</script>
then when the function is called, all DOM nodes are available. Some, like images, may not be fully loaded, but their elements have been created.
If it means you have the script in the body and aren't using the load event, you should move the script to the bottom of the page (e.g. just before the closing body tag) and see if that fixes the issue.
Okay, instead of calling functions with
body onload, use jQuery's ready() function, or, if you don't want to use jQuery, you can use pure javascript, but this is up to you:
// jQuery
$(document).ready(function() {
var post = document.getElementsByClassName("post"),
x = post[i].getElementsByClassName("MyDiv")[0].innerHTML;
});
// JavaScript
window.onload = function initialization() {
var post = document.getElementsByClassName("post"),
x = post[i].getElementsByClassName("MyDiv")[0].innerHTML;
}
A few side notes, I don't know what the use of innerHTML
is, and also if you're doing a for loop with i then definitely
post that code, that's kind of important.
After some discussion, my answer seems to have worked for you, but you can also place your script at the end of your body tag as #RobG has suggested.

Removing a script tag with a specific content using jquery

I have a page that i dont have access to its an obvius site. I would like to remove a script html tag with a content. For now i have this but is not working. I am using userscripts like coding!
function main(){
var def = $('script[type="text/javascript"]').html();
$('script[type="text/javascript"]').each(function() {
if (def == 'document.write("<scr"+"ipt type=\'text/javascript\' src=\'http://storing.com/javascripts/"+(new Date()).getTime()+"/3e155555e1b26c2d1ced0f645e_1_1.js\'></scr"+"ipt>")')
$('script[type="text/javascript"]').remove();
}
}
UPDATE:
<script type="text/javascript">document.write("<scr"+"ipt type='text/javascript' src='http://somedomain.com/javascripts/"+(new Date()).getTime()+"/3e1a0cd37f25a6e1b26c2d1ced0f645e_1_1.js'></scr"+"ipt>")</script>
This is the whole script what i want to remove... it inserts a div that i am removing right now i just wanted to know if there is any other method. BUt as i see the only is the hosts file thing :)
I don't believe this will work, since a loaded script will already have run.
That said, you probably want something like this:
$('script').each(function() {
if (this.src.substring(0, 31) === 'http://storing.com/javascripts/') {
$(this).remove();
}
});
It's impossible to match the <script> tag based on the output of .html() because that only returns the contents of the element, and not the outer <script> element nor the element's attributes.
When a script is loaded in a page, it is evaluated and executed by the browser immediately after. After the script has been executed, the content of the script tag is irrelevant.
You might be able to achieve what you want by unbinding the events which might have been loaded by the script. Are there any events you want to disable?
If the script is in a certain domain and you want to block all traffic to it, you could add the following entry to your hosts file:
127.0.0.1 storing.com
This will prevent the request to reach it's destination.

Separating JQuery Scripts with Selectors in External file does not work?

I have a JQuery Selector and an event associates with it.I want to keep it in external file and just copy and directly save it. The thing which I see is that the external JavaScript that has the selector does not work. Can someone explain Why?
NOTE: I am able to use the same function within my HTML file but when externalize it. It just doesn't work .
The script that I have is as follows:-
$('#pervious').click(function() {
var presentSlide = $('.visible').attr('id');
var tempArr = presentSlide.split("-");
var persentSlideNo = tempArr[1];
var perviousSlideNo = Number(persentSlideNo) - 1; if (perviousSlideNo > -1)
{
var perviousSlide = "Slide-" + perviousSlideNo;
$('#' + presentSlide).fadeOut('slow',function(){
$(this).removeClass('visible').addClass('hidden');
});
$('#' + perviousSlide).fadeIn('slow',function(){
$(this).removeClass('hidden').addClass('visible');
});
}
});
How are you including this script?
Note that it needs to go below the definition of your id=pervious element, or it needs to go after it (e.g. document.ready), otherwise the element won't exist, and there won't be anything to bind to.
UPDATE
To restate, it needs to execute AFTER the pervious element gets created. Putting it in an external document is likely causing it to execute BEFORE the pervious HTML element is created, and therefore it doesn't work. You can put it in an external file, sure, just make certain that the element gets loaded, e.g.
$(document).ready(function() {
$.getScript('http://yoursite.com/extrascript.js');
});
After you have determined you are actually linking to it by doing an alert, wrap your code like so:
$(function(){
// place your code inside here for ready event
});
What you are doing is running your selector before the document is ready. The selector runs before the dom is there and there is no results in the selector so you don't attach anything.
You have to include scripts with the form of: (including the closure tag as such)
<script src="myexternal.js" type="text/javascript"></script>
Not any of these:
<script src="myexternal.js" type="text/javascript" />
<script src="myexternal.js" />
<script src="myexternal.js" ></script>
form or it will not always get rendered properly and thus not execute.
and of course, since you are using jQuery, you should put YOUR code AFTER the jQuery library link AND include your code in a document ready as others have demonstrated.

How can we get an initial piece of JavaScript to run without referencing a function in your XHTML page?

Can we you get our JavaScript to run in the first place to
assign an event handler?
How can we get an initial piece of JavaScript to run without referencing a function in your XHTML page?
Just put a script tag in the body of your page and it will run as the page is rendered.
<script type="text/javascript">
// code goes here
</script>
Any code you put in a <script type="text/javascript"> tag will be executed immediately. Put it in your <head> and it will run before anything else. Put at the end of the <body> and it will run last.
Do keep in mind that the DOM may not be fully initialized in either of those cases. If you need the DOM use window.onload or jQuery's $(document).ready()
Also 'XHTML' and 'HTML' are not the same. XHTML is a very strict subset of HTML that in my opinion does nothing to improve upon regular HTML but it does allow for some fanciness. It has no effect whatsoever on JavaScript.
As you've tagged jQuery the way to do this is simply by including a ready function, e.g.
$(document).ready(function () {
// Assign your event handlers
});
Just put this code within a <script type="text/javascript"> block within your page.

Categories