Javascript at head does not work [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 8 years ago.
Given this html code that we are not allowed to edit
<!doctype html>
<html manifest="survey.manifest">
<head>
<title>Offline Survey Application</title>
<link rel="stylesheet" href="styles/survey.css" type="text/css">
<script type="text/javascript" src="scripts/survey.js"></script>
</head>
<body>
<!--should be empty --->
</body>
</html>
<!-- YOU ARE NOT ALLOWED TO EDIT THIS FILE!!! -->
I cannot seem to make my javascript work. But if i placed the script element at the body the whole script shows up. The problem is that we are not allowed to do that though. Is there any other way to make it work?
EDIT: I am aware that the script runs before the other elements are loaded. I can't go with moving it elsewhere since the file would have been modified :/

It could be due to the fact that the script only works when the page has finished loading, but by placing the code in the head, you load the script first. To get around this, you could try replacing your current script code with this:
<script type="text/javascript" src="scripts/survey.js" defer></script>
This ensures that the code only loads once the page has finished loading.

Presumably, your script is attempting to modify the DOM and tries to access the body element.
At the time the script is initially loaded and run, the body does not exist.
Move your code to a function, and bind that code as a load event handler. (addEventListener('load', someFunction);).

Related

Where is the ideal place to load javascripts in html? [duplicate]

This question already has answers here:
Where should I put <script> tags in HTML markup?
(21 answers)
Closed 2 years ago.
I understand inline javascripts scattered through html code like the following example is bad
<html>
<head>
</head>
<body>
<p> Foo <script></script></p>
</body>
</html>
However, after coding for a while, understanding that loading Javascripts at the end of the document is the best way to go. I do see a lot of the sites that conform to loading scripts at the end of their document, do so in the following manner :
<html>
<head>
</head>
<body>
<p> Foo </p>
<script></script>
</body>
</html>
What is not made clear, is why not :
<html>
<head>
</head>
<body>
<p> Foo </p>
</body>
<script></script>
</html>
.. as this is outside the body tag which means that the body (in theory) can process faster and still load your scripts before finalizing on </html>.
Or even this :
<html>
<head>
</head>
<body>
<p> Foo </p>
</body>
</html>
<script></script>
Each variation will have (in theory) different performance results, and/or may break functionality in the page depending on the script contents of course.
Of the above formats, which one is the ideal place to load javascripts that would have the highest performance gain without breaking html ?
The best place at the end of the body tag, like
<html>
<head>
</head>
<body>
some html body tags
.
.
.
<script> external or inline </script>
</body>
</html>
If you do like so, then the html will load quicker and main pros is that all your ids and classes will get assigned otherwise sometime if you put script above html, then there might be a chance that you try to get an element by id that is not yet assigned in DOM
[UPDATE]
Here is an example code that Bootstrap is using in their own website: http://getbootstrap.com/getting-started/
you can find this code under Basic template Heading:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<h1>Hello, world!</h1>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
As noted here, the script tag won't validate outside of the body or head tags. However, you want to place it as far down as possible, so that the rest of the page loads first, to avoid errors. This leaves us with the place furthest down, but inside the body and head tags: just before the closing body tag.
<html>
<head>
</head>
<body>
<p> Foo </p>
<script></script>
</body>
</html>
If you know how the browsers work it will be easy to know where to put it.
First of all it's invalid to include your script after the body or the html element. Only comments and the closing tag for html are allowed after the body. Some browser will do recovery but you shouldn't depend on that.
You may include it any where in the body or the head but you should know that script take the browser attention may be for while and I will stop rendering the dom. That's very bad for user experience so the best place to include it just at the end of the body element.
Like in the example :
<html>
<head>
</head>
<body>
<p> Foo </p>
<!-- ... -->
<script></script>
</body>
</html>
One more thing if you include the script at the top of the page and that script will manipulate the dom that may cause an error if the dom isn't ready yet. The script searching for element which is not exist yet. And it will be very confusing when it runs at time and it doesn't run in another time. You may check the answers for similar questions here and here
How browsers work: As you can see from here, most of the browsers parsing the html elements top to bottom in elements tree hieararchy.
So, when you put a script just before </body> tag, make sures that most of the elements has been loaded or at least parsed. Or, you just need to wait for document.readyState.
Also, by putting your script below </body> tag is semantically not good. But, you can do it and it won't make a difference for the performance.
Important thing to note is the following:
If you put the script in the head tag HTML page rendering is blocked until the script is downloaded.
The more scripts you will put there the slower your page will load.
That’s why an advanced approach is to put the scripts at the bottom of the BODY, and in this case the user can start interacting with a page before the Javascript has Loaded.
You will put the scripts in HEAD only if they MUST be available before the page is shown.
Best way to load your java-script at the end of body tag, but in some case when you use third party script, it need be load before control initialize.
<html>
<head>
</head>
<body>
...........
<script></script>
</body>
</html>
JavaScript is a render blocking resource. So when browser is parsing HTML document and encounters script in between, the control is passed to js engine. Which runs the script and returns the control to browser again.
<html>
<head>
<script src="/main.js" />
</head>
<body>
<script>
//some inline script
</script>
</body>
</html>
So when broswer encounters the script tag in header, it passes the control to js engine. Now beacuse the script is being loaded from network, js engine will wait for script to load. After that it will be executed. Then document parsing will resume. (Inline script in head would have worked faster as network delay would be avoided)
Same goes for inline script. Situation gets complex if CSS is also present along with javascript. If a CSS is also being loaded from network in the head, js engines will wait for it too. So there are 2 dependencies now.
So it is best to add js at the bottom and CSS at top generally (to avoid Flash of Unstyled Content).
A good read for the same is present here :
Critical Rendering Path

How to put javascript in html file

Let me re-explain the whole question.
I want to add this in my website http://www.w3schools.com/howto/howto_js_slideshow.asp
So for this, i have to make a external java file (internal may work, but i want external).
So when i paste the java code in my html file in body tag, the script works fine. So that means, nothing wrong with the script. But when i put the same thing in a different external file, the script is not working.
So the problem must be in the head tag, where i write the external file location. This is my head tag
<head>
<title>FFH</title>
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
<link rel="shortcut icon" type="image/x-icon" href="images/ffh.ico" />`
<script type="text/javascript" src="myscript.js"></script>
Yes, the "myscript.js" is in the same folder and i am 100% sure about it.
put your html file and javascript file under the same folder.
Following can be a reason for your issue
Invalid src path in the script tag
Javascript might be disabled in your browser.
You have a script error/exception that stopped entire page's script execution.
Maybe you have an Ajax request that won't work if your open it as a local file protocol. e.g., file://
What can you do?
It is right time for you to know about and use your developer tools available in your favorite browser.
See if it shows 404 or some other error. Then update your SO question with the exact error message that you see. We would be happy to help.
Revised answer based on provided w3c link:
Now we know the exact problem.
You can not add that script tag to the head of the HTML. Because the elements that you refer in the script are not available at that time of execution. Move the script tag just before the end of body tag (all your carousal tags/elements should be present before the script tag) . Then It would work as expected.
If you still want that script tag to be in the head section, then you have to initialize your carousal/slider in DOM ready event or window.Onload event.
Still my earlier comment is relevant, because you can use developer tools in your browser to find out the exact error statement.
As stated in other answers, script-tag may not work if it is located in <head> tag. Try adding it right before </body>.
+don't call it java, they have nothing else in common except name :)

Load jQuery in PHP page - no head tags

This is probably super simple answer, but I just can't figure this out.
Basically, I've got a php page only starting with opening <?php tag.
I've got a jquery script that I need to call on this page.
<script type="text/javascript">
$('input[name="_manage_item"]').click(function() {
$('input[name="_item"]')[this.checked ? "show" : "hide"]();
});
</script>
From what I researched, I need to load the script by placing
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
into the <head> tags of the page.
But my page doesn't have the html <head> or <body> tags. Where do I call the script then ?
I tried to place it in front of the opening <?php tag, but that broke the page.
What is the correct way of doing this ?
You can place your javascript outside the php tags at the bottom of you page. But when you use the php in a web page, you should add the html and head and body tags. A simple php page could look like this:
<html>
<head>
<!-- stylesheets and javascript -->
</head>
<body>
<?php
//You php-code
?>
<!-- scripts at the end of the page to let the side load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$('input[name="_manage_item"]').click(function() {
$('input[name="_item"]')[this.checked ? "show" : "hide"]();
});
</script>
</body>
</html>
Relying on your wordpress tag, I suggest you to read this article. There are described all details concerning javascript usage within wordpress. Probably the most common way is to use wp_register_script() function.
The safe and recommended method of adding JavaScript to a WordPress generated page, and WordPress Theme or Plugin, is by using wp_enqueue_script().
I would also advise you to merge your code to a distinct file, and load it straight after jquery library. It is a good practice, because in such a way browser can cache your script and would not download it on every page request. You should also wrap it into a $( document ).ready() function, to be sure that it will be executed only only when document is in ready state.

<script> tag makes HTML contents disappear

This is such a wierd problem. I have the following extremly simple HTML code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery.js" />
</head>
<body>
test
</body>
</html>
If I run this page in a web browser, I get nothing at all, just an empty page. If I remove the script reference line entirely, then I get a blank page that displays "test", like it should. This tells me that there is some issue in the jquery.js file, but I have tried 3 different versions of jquery and the one I am using is the latest from the jquery.com website. For the life of me, I can't figure out what I'm doing wrong. I know it will turn out to be simple though.
script tags cannot be self-closing. You need the closing </script> tag:
<script type="text/javascript" src="jquery.js"></script>
Not including the closing tag means the whole content up to and including </html> is treated as the body of the script element. Because the document is then incomplete, your browser closes the script, head and html elements and inserts an empty body element.
you need to close your script tag otherwise it thinks everything after is javascript to be executed...
<script type="text/javascript" src="jquery.js"></script>
The <script> tag is not self-closing, so you'll need a separate </script>:
<script type="text/javascript" src="jquery.js"></script>
See Why don't self-closing script tags work?
You're confusing HTML and XHTML.
In HTML, the script tag is not self closing, so you must write <script src="jquery.js"></script>.
In XHTML, you must set your XML namespace(<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">) and send the document with the correct mime type.

Are there negative effects from not loading jQuery in the <head> tag?

I currently am working on a large site with many different issues to contend with. One being that I have no easy way to include a script into my <head> without manually doing it for 500+ pages.
I have the possibility to include jQuery.min just inside the <body> tag from an include located there.
My question is, aside it not being a standard implementation, would there be any negative effects from not loading jQuery within the <head> tag? Will all the functions be available?
I am aware that if I do this, I will not be able to call jQuery from within the <head> or before this include... that's okay.
example:
<head>
Standard Head Stuff
</head>
<body>
<div>Some Content</div>
<!-- My Include is roughly here -->
<script type="text/javascript" src="jquery.min.js"></script>
<div>More content</div>
<script type="text/javascript">
$(document).ready(function(){
// Put my jQuery commands here
});
</script>
</body>
The only issue is that a page is loaded from top to bottom and so if you were to place the include statement into the header than you would be assured that the library would be loaded immediately. Otherwise the library may only be loaded at a later time which can cause a delay in some effects potentially.
Head or body, inline code will execute when phrased. Code is generally placed in the head so external libraries can be loaded before the page is (so effects can be run on dom ready). Code in the body will be run once the dom is done with the header code, and done loading page elements (once in the body, elements are loaded from top to bottom). So any code in the body will be executed once the page had loaded (up to that point)

Categories

Resources