JavaScript-Leistung
- Vorherige Seite JS-Fehler
- Nächste Seite JS-Reservewörter
How to speed up your JavaScript code.
Reduce activity within loops
Loops are often used in programming.
With each iteration of the loop, each statement in the loop, including for
statements, will be executed.
Statements or assignments that can be placed outside the loop will make the loop run faster.
Poor code:
var i; for (i = 0; i < arr.length; i++) {
Better code:
var i; var l = arr.length; for (i = 0; i < l; i++) {
Bad code will access the array's length
.
Good code accesses the property outside the loop length
properties, making the loop faster.
Reduce DOM access
Accessing the HTML DOM is very slow compared to other JavaScript.
If you expect to access a DOM element several times, access it only once and use it as a local variable:
Beispiel
var obj; obj = document.getElementById("demo"); obj.innerHTML = "Hello";
Reduce the size of the DOM
Try to keep the number of elements in the HTML DOM to a minimum.
This will always improve page loading and speed up rendering (page display), especially on smaller devices.
Every time you try to search the DOM (for example getElementsByTagName
)will benefit from a smaller DOM.
Avoid unnecessary variables
Do not create new variables that you do not intend to store values.
You can usually replace the code with:
var fullName = firstName + " " + lastName; document.getElementById("demo").innerHTML = fullName;
Use this code:
document.getElementById("demo").innerHTML = firstName + " " + lastName
Delay JavaScript loading
Please place the script at the bottom of the page to make the browser load the page first.
Während das Skript heruntergeladen wird, startet der Browser keine anderen Downloads. Darüber hinaus können alle Parsing- und Rendering-Aktivitäten blockiert werden.
Die HTTP-Spezifikation definiert, dass der Browser nicht mehr als zwei Elemente gleichzeitig herunterladen sollte.
Eine Möglichkeit ist die Verwendung des defer="true"
.Die defer-Attribut legt fest, dass das Skript nach dem vollständigen Verarbeiten der Seite ausgeführt werden soll, es ist jedoch nur für externe Skripte gültig.
Wenn möglich, können Sie nach dem vollständigen Laden der Seite Skripte über Code zur Seite hinzufügen:
Beispiel
<script> window.onload = downScripts; function downScripts() { var element = document.createElement("script"); element.src = "myScript.js"; document.body.appendChild(element); } </script>
Vermeiden Sie die Verwendung von with
Vermeiden Sie die Verwendung mit
Schlüsselwort. Es hat einen negativen Einfluss auf die Geschwindigkeit. Es kann auch die JavaScript-Scope verwirren.
Im strengen ModusNicht erlaubt mit-Schlüsselwort.
- Vorherige Seite JS-Fehler
- Nächste Seite JS-Reservewörter