What's wrong with my code in HTML

JavaScript / Tutorials / DOM / Integration in HTML


JavaScript is a programming language that is used as an additional technology integrated in websites becomes. In modern web design, websites are given a behavior layer in addition to the content structure and appearance.

DOM scripting (Unobtrusive JavaScript) [edit]

In this concept, JavaScript has the task of adding "behavior" to the document. This means that the document reacts to certain user events and z. B. Makes changes in the document. This interactivity is automatically added to the document - there should be no JavaScript in the HTML code in the form of event handler attributes (onload, onclick, onmouseover, etc.). In the ideal case there is one or the other element in the element in order to integrate an external JavaScript file, which in turn becomes active and attaches the event handlers to the respective elements. For this purpose, elements to which a certain behavior should be added, e.g. B. marked with a class or even given an ID if necessary.

Up-to-date scripts are automatically activated when the document is loaded and start event monitoring on the relevant elements. This application of JavaScript is called Unobtrusive JavaScript, "Unobtrusive" JavaScript, or else DOM scripting.

Involvement [edit]

JavaScript source texts are noted or referenced in HTML in a script element. The element may be noted in or in the HTML document.

script elements may also be noted within flow elements.

Attributes in the element [edit]

<script>…</script>
Note:
  • In HTML5 you can omit the specification of the MIME type - in older HTML variants this specification is necessary.
  • The language attribute was classified as deprecated and must be omitted.

Write down JavaScript code directly in HTML [edit]

<!doctype html><html><head><metacharset="utf-8"><title>JavaScript: Hallo Welt</title><script>alert("Hallo Welt!");</script><noscript> Sie haben JavaScript deaktiviert. </noscript></head><body><p>Diese Seite tut nichts weiter, als eine Hinweisbox auszugeben.</p></body></html>
In the example above, a message window with the text "Hello world!" Is displayed on the screen using JavaScript.
Recommendation: With the HTML element you can define areas that are displayed when JavaScript is deactivated.

It used to be common to enclose scripts in a CDATA block. The need for this only existed for XHTML documents, but was understood by many as “this is how it must be” and used everywhere. It didn't bother either. There is also an XML notation for HTML 5, but as long as you do not want to process such a document with an XML tool, the CDATA notation is no longer necessary.

Note: Inline scripts in an HTML file are normally ignored by the HTML parser. So you don't have to be careful not to use characters like & or

Referencing JavaScript files in HTML [edit]

Noticing JavaScript directly in HTML is generally bad practice. It is much better to write down scripts in your own files and then integrate them. The file is executed in the appropriate place as if the code was written down directly. You can embed these external JavaScript files in any number of websites.

functionQuadrat () {varEingabe = document.getElementById ('Input'); varErresult = Input.value * Input.value; alert ("The square of" + Input.value + "=" + Result); Input.value = 0;} varlos = document.getElementById ('los'); los.addEventListener ('click', square, true);
The external JavaScript file contains a function in which the input field is also accessed. The variable is assigned the square of the value of the input. This is then issued with a brief explanation. The value of the entry is then reset.

In the last 2 lines, the button is accessed with the id and assigned to it via the event handler. A click on the button calls up the function.

In order for this event handler to be assigned, the element must already exist. Therefore, the script should either be called at the end of the HTML document or after the final loading of the page (using) a function.
for the integration of the separate JavaScript file "quadrat.js" in an HTML file. This is how it looks
<!DOCTYPE html><htmllang="de"><head><metacharset="utf-8"><title>externes JavaScript in HTML einbinden</title></head><body><h1>externes JavaScript in HTML einbinden</h1><main><inputtype="number"id="Eingabe"value="0"size="3"><buttontype="button"id="los">Quadrat errechnen</button></main><scriptsrc="quadrat.js"></script></body></html>

The src-Attribute (source = "Source") has the URI to the script as its value. (More information about referencing in HTML)

Note: In the example, the button receives an event handler with addEventListener from the external script. Therefore, the external script must be called at the end of the HTML document so that the button element is already available when the event handler is to be attached, so that the functionality is guaranteed. If the script is referenced in the head, the event handler must be loaded e.g. by at the end of the loading process.

Script in the head or at the end of the body element? [Edit]

A question that is asked again and again is which of the two positions is better.

When a browser loads a web page, it follows a fixed routine:

  1. The browser fetches the HTML file
  2. The HTML markup is parsed
  3. The parser encounters a script element that references an external JavaScript
  4. The browser sends a request that the script should be loaded. In the meantime, the parsing of the rest of the HTML markup will be stopped.
  5. After a while, the script will be downloaded and executed.
  6. The browser continues parsing the rest of the HTML.

Why is there an interruption in step 4? Scripts can insert or change HTML with document.write () or other DOM manipulations. So the parser waits for the script to download and run before parsing the rest of the document.

For this reason, many people used to recommend integrating JavaScript at the end by placing the script element in front of the closing body tag. However, this approach has the problem that the browser cannot download scripts until the entire HTML document has been parsed. Especially with larger pages with many stylesheets, scripts and integrated libraries, this can lead to a poorer conversion rate if users give up in exasperation after waiting unsuccessfully for the website.

So scripts should be loaded as soon as possible.

Conclusion: in the head

You can use the async and defer attributes to tell the browser that it can continue parsing while it is downloading scripts.

Details: caniuse.com

<scriptsrc="script1.js"async></script><scriptsrc="script2.js"async></script>

Even on the few old browsers that do not yet support these attributes, your pages will load correctly.

Note: Often, elements in the DOM are accessed in JavaScript that were not yet parsed when the script was loaded. Therefore you have to call it up after loading the page. This works best with the DOMContentLoaded event.

However, when using async and defer you need to keep an eye on the browser's processing order.

Inline scripts without and external scripts that have no - or - attribute stop processing the HTML document and are executed as soon as they are encountered. In the case of external scripts, this can initially mean access to the server if they are not in the cache and cause a noticeable delay.

All other scripts are placed in a queue. If the script is external and not in the cache, the browser requests it from the server.

After the document has been loaded, processing of the queue begins. The scripts set with are processed strictly in the order in which they were set, regardless of the order in which the server delivered them. The event is only signaled after the last script.

The scripts set with are executed in the order in which they become available. This can be before the first script, between two scripts or after the last script.

That means:

  • Scripts without or become always executed before the event. A handler for the event, which you register in a script, is definitely executed.
  • The scripts are also running always before the event. A handler for the event that you register in such a script is definitely executed.
  • A script can be executed before or after. A handler for the event is only executed if the script was available in good time. You can use the property of the object to determine in a script whether it has already triggered. If it contains the value, it is still to come, otherwise it is already over.
  • But beware: An old browser, whether or not it supports it, loads the script when it encounters it and executes it immediately. Such browsers may also not support the property of the document, or Internet Explorer versions 9 and 10 can report an incorrect readyState. If you are dependent on the existence of DOM objects, try to find one in your script. If it is still missing, register your logic in a DOMContentLoaded handler.
Control of script execution in an async script
Let us assume that your async script wants to register a click handler for the button with the ID "saveButton". The actual work of the script is bundled in the function. The preamble of the script first checks whether the button can already be found. If so, he calls the registration function directly. Otherwise it is registered as an EventHandler for DOMContentLoaded.
if (document.getElementById ("saveButton")) registerClickHandler () elsedocument.addEventListener ("DOMContentLoaded", registerClickHandler); functionregistriereClickHandler () {document.getElementById ("saveButton"). / Code to save here});}

Note

In the examples in the wiki, you should always include JavaScript in, because the existing scripts are displayed in the Frickl editor, but are overwritten by the original code in the HTML markup when executed. --MScharwies (discussion) 11:55, Jan. 11, 2017 (CET)

Web links [edit]