JS TutorialLesson #125
JavaScript Performance
How to speed up your JavaScript code.
How to speed up your JavaScript code.
Share
Reduce Activity in Loops
Loops are often used in programming.
Each statement in a loop, including the for statement, is executed for each iteration of the loop.
Statements or assignments that can be placed outside the loop will make the loop run faster.
Bad:
Example Code
javascriptfor (let i = 0; i The HTTP specification defines that browsers should not download more than
> two components in parallel.
An alternative is to use `defer="true"` in the script tag. The defer attribute specifies that the script should be executed after the page has finished parsing, but it only works for external scripts.
If possible, you can add your script to the page by code, after the page has loaded:
### Examplehtml
window.onload = function() {
const element = document.createElement("script");
element.src = "myScript.js";
document.body.appendChild(element); };
```
Avoid Using with
Avoid using the with keyword. It has a negative effect on speed. It also clutters up JavaScript scopes.
The with keyword is not allowed in strict mode.
Interactive Code Examples
Bad:
javascriptJavaScript syntax and algorithm demonstration.
for (let i = 0; i < arr.length; i++) {Better Code:
javascriptJavaScript syntax and algorithm demonstration.
let l = arr.length;
for (let i = 0; i < l; i++) {JS Example 3
javascriptInteractive runnable JavaScript example from EA Academy.
Live Output Preview:
Example 4
javascriptJavaScript syntax and algorithm demonstration.
let fullName = firstName + " " + lastName;
document.getElementById("demo").innerHTML = fullName;Example 5
javascriptJavaScript syntax and algorithm demonstration.
document.getElementById("demo").innerHTML = firstName + " " + lastName;JS Example 6
htmlJavaScript syntax and algorithm demonstration.
<script>
window.onload = function() {
const element = document.createElement("script");
element.src = "myScript.js";
document.body.appendChild(element);
};
</script>