Document

Is it wrong to place the tag after the tag? [duplicate]

It’s not wrong. It will cause an alarm on validators, but it will run on most browsers. It is not wrong, but it is not valid.

10 Answers 10

It won’t validate outside of the or tags. It also won’t make much difference — unless you’re doing DOM manipulations that could break IE before the body element is fully loaded — to putting it just before the closing .

@epalla: if you put the script right at the end of the body tag there’s no other content left to load by the time it gets there, so there should be little difference between placing it outside or just inside. You then have the added benefit of your page still validating, which was the point I was trying to make in my answer.

Yep, I was agreeing with you since your answer is good. I just wanted to add that there is a reason for putting JS at the bottom of the page instead of in the head as we’ve done for a long time.

@PHPst: well, invalid code may be subject to side effects in certain browsers. Either way, I don’t see how its indentation being one tab-width less than the code above it makes it look any cleaner.

@PHPst: I would expect browsers to cope with it if you really want to write your code that way. I’d still recommend writing your code to validate, however.

@technosaurus: there’s always

Only comments and the end tag for the html element are allowed after the end tag for the body.

You can confirm this with the specification or a validator.

Browsers may perform error recovery, and the HTML specification even describes how to recover in that situation, but you should never depend on that.

It is also worth noting that the usual reason for putting the script element at the end is to ensure that elements the script may try to access via the DOM exist before the script runs.

With the arrival of the defer attribute we can place the script in the head and still get that benefit while also having the JS be downloaded by the browser in parallel with the HTML for better performance.

This is a better answer. There are too many new browsers out there with mobile coming into play to risk doing it wrong when all you have to is cut and paste a single closing tag.

Note that defer only applies to external script files (i.e. you must also specify src attribute). You cannot «defer» a element that contains script.

As Andy said, the document will be not valid, but nevertheless the script will still be interpreted. See the snippet from WebKit for example:

void HTMLParser::processCloseTag(Token* t) < // Support for really broken HTML. // we never close the body tag, since some stupid web pages close it before // the actual end of the doc. // let's rely on the end() call to close things. if (t->tagName == htmlTag || t->tagName == bodyTag || t->tagName == commentAtom) return; . 

Internet Explorer doesn’t allow this any more (since version 10, I believe) and will ignore such scripts.

Читайте также:  Using function in class python

Firefox and Chrome still tolerate them, but there are chances that some day they will drop this as non-standard.

And yet Google does this in their example of how to do G+ sign-in, with «last updated April 10, 2014». I got it from the version for Java on the server (developers.google.com/+/quickstart/java) but presumably it is the same HTML+js for all.

Procedurally inserting an «element script» after an «element body» is a «parse error» by the recommended process by W3C. In «Tree Construction» create an error and run «tokenize again» to process that content. So it’s like an additional step. Only then can it run the «Script Execution» — see the scheme process.

Anything else is a «parse error». Switch the «insertion mode» to «in body» and reprocess the token.

Technically, by the browser, it’s an internal process how they mark and optimize it.

Yes. But if you do add the code outside it most likely will not be the end of the world since most browsers will fix it, but it is still a bad practice to get into.

Modern browsers will take script tags in the body like so:

Basically, it means that the script will be loaded once the page has finished, which may be useful in certain cases (namely DOM manipulation). However, I highly recommend you take the same script and put it in the head tag with «defer», as it will give a similar effect.

What would be useful is if script tags had a event attribute that could be defined to determine when to parse the script. So you have event=»load» event=»DOMContentLoaded» for running the script after the DOM is created or event=»beforeunload» on the window beforeunload event. Example, .

Putting it in the head with defer doesn’t have the same effect; with defer, in the head: The script is fetched asynchronously, and it’s executed only after the HTML parsing is done. Whereas if you put the script at the end of the body: The HTML parsing is done without any pauses, and when it finishes, the script is fetched, and executed.

@PeterMortensen it’s not wrong to do anything especially in something as lax as html 😂 I was referring to potentially unexpected behavior where the document hasn’t actually finished loading yet depending on where you put the script tag in the body.

Technically you shouldn’t be able to place the script tag after the body tag since rendering of the page content ends with the body (or is it the head?.)

But browsers are somewhat fault tolerant (although I wouldn’t depend on this as a universal truth because you just might never know) and they’d:

  1. move the script tag back into the body tag if it appears outside the body or html tag.
  2. move the script tag into the head tag if it appears before the document declaration.
  3. leave it as is if it appears (in source order) anywhere else it appears in the document.
  1. use the defer or async attribute with the script tag in the head, or
  2. use the script tag(s) right before the closing body tag
Читайте также:  Класс files java nio

This norm is an accepted practice/convention and is guaranteed to remove any doubts.

Also while you are play safe and do the most [reasonable] thing, keep in mind that what you need to [then] worry about is the performance because the loading/downloading, parsing and interpretation of the internal/external sourced file(s) is/are dependent on where the script(s) tag occurs, even if you were using defer or async.

            

Content goes here

Content goes here

Источник

Append Tag to Body?

I tried to run it in JSFidle and there where no problems. When I run it on my html page which runs on a demo server I get the following error in the console:

Uncaught TypeError: undefined is not a function 

enter image description here

What causes this error and how can I prevent it? Edit: Removing the type text/javascript does not change anything.

In your jsfiddle you have the option for JS to run on onLoad which practically makes your code to execute after ` window.onload` and thus the loadScript() function never to be called

2 Answers 2

The error you are getting is because there is no initialize() function. If you declare one there will be no error.

function loadScript() < var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize'; document.body.appendChild(script); console.log('loadScript'); >function initialize() < console.log('initialize'); >window.onload = loadScript; 

I tried to run it in JSFidle and there where no problems.

Incorrect. On JSFiddle you have a different problem.

There you run your code when the document load event fires. That code defines a function and assigns an event handler for the document load event. Since that event has already fired, the function never runs. You don’t get an error because the code doesn’t get as far as it does when you test in your standalone document.

When I run it on my html page which runs on a demo server I get the following error in the console:

In this case, the code is running successfully.

The load event fires. The loadScript function runs. The script element is appended to the page. Google’s script runs.

You get an error because you said:

So the script you are requesting from Google tries to call initialize() , but you haven’t defined that function so you get an error instead.

See also the documentation which includes this example:

function initialize() < var mapOptions = < zoom: 8, center: new google.maps.LatLng(-34.397, 150.644) >; var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); > function loadScript() < var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp' + '&signed_in=true&callback=initialize'; document.body.appendChild(script); >window.onload = loadScript; 

Источник

How to append to Head or Body Using Javascript?

I have a JavaScript problem. I searched on google how to append using javascript and I found an example. I want to manually append a script tag to head or body, but the example just appends in the head. I edited the example so that the script tag can be appended in the head or body, but the code doesn’t work. Can anyone help me fix my problem? And please show me the demo on jsfiddle 😀 Thanks 🙂 Here my script:

//JS //Defined with loadjscssfile("yourcssurl.js", "js", "head"); or addCss("yourcssurl.js", "js", "body"); //CSS //Defined with loadjscssfile("yourcssurl.css", "css", "head"); or addCss("yourcssurl.css", "css", "body"); function loadjscssfile(filename, filetype, pos) < if (filetype == "js") < //if filename is a external JavaScript file var fileref = document.createElement('script') fileref.setAttribute("type", "text/javascript") fileref.setAttribute("src", filename) >else if (filetype == "css") < //if filename is an external CSS file var fileref = document.createElement("link") fileref.setAttribute("rel", "stylesheet") fileref.setAttribute("type", "text/css") fileref.setAttribute("href", filename) >if (typeof fileref == filetype) < document.getElementsByTagName(pos)[0].appendChild(fileref) >else if (typeof fileref != "undefined") < document.getElementsByTagName("head")[0].appendChild(fileref) >> loadjscssfile("myscript.js", "js", "body") //dynamically load and add this .js file loadjscssfile("javascript.php", "js", "body") //dynamically load "javascript.php" as a JavaScript file loadjscssfile("mystyle.css", "css", "body") ////dynamically load and add this .css file 

And here is the original script, before I edited: Dynamically loading an external JavaScript or CSS file Sorry for my bad english 🙂

Читайте также:  Документ без названия

Источник

JavaScript Where To

In HTML, JavaScript code is inserted between tags.

Example

Old JavaScript examples may use a type attribute: .
The type attribute is not required. JavaScript is the default scripting language in HTML.

JavaScript Functions and Events

A JavaScript function is a block of JavaScript code, that can be executed when «called» for.

For example, a function can be called when an event occurs, like when the user clicks a button.

You will learn much more about functions and events in later chapters.

JavaScript in or

You can place any number of scripts in an HTML document.

Scripts can be placed in the , or in the section of an HTML page, or in both.

JavaScript in

In this example, a JavaScript function is placed in the section of an HTML page.

The function is invoked (called) when a button is clicked:

Example

Demo JavaScript in Head

JavaScript in

In this example, a JavaScript function is placed in the section of an HTML page.

The function is invoked (called) when a button is clicked:

Example

Demo JavaScript in Body

Placing scripts at the bottom of the element improves the display speed, because script interpretation slows down the display.

External JavaScript

Scripts can also be placed in external files:

External file: myScript.js

External scripts are practical when the same code is used in many different web pages.

JavaScript files have the file extension .js.

To use an external script, put the name of the script file in the src (source) attribute of a tag:

Example

You can place an external script reference in or as you like.

The script will behave as if it was located exactly where the tag is located.

External scripts cannot contain tags.

External JavaScript Advantages

Placing scripts in external files has some advantages:

  • It separates HTML and code
  • It makes HTML and JavaScript easier to read and maintain
  • Cached JavaScript files can speed up page loads

To add several script files to one page — use several script tags:

Example

External References

An external script can be referenced in 3 different ways:

  • With a full URL (a full web address)
  • With a file path (like /js/)
  • Without any path

This example uses a full URL to link to myScript.js:

Example

This example uses a file path to link to myScript.js:

Example

This example uses no path to link to myScript.js:

Example

You can read more about file paths in the chapter HTML File Paths.

Источник

Оцените статью