Skip to content

Commit 0ac23f4

Browse files
committed
learn about loading JSs dynamically
1 parent 80a529b commit 0ac23f4

File tree

4 files changed

+48
-0
lines changed

4 files changed

+48
-0
lines changed

Advanced-DOM-APIs/README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
| [Working with Element Sizes and Positions](#working-with-element-sizes-and-positions) |
88
| [Handling Scrolling](#handling-scrolling) |
99
| [Working with `<template>` tag](#working-with-template-tag) |
10+
| [Loading Script Dynamically](#loading-script-dynamically) |
1011

1112
Below topics will be covered and for its practical application, [Planner Project](project_planner/) will be used as reference where concept of classes and functions are demonstrated:
1213

@@ -196,3 +197,35 @@ Readings:
196197
- [HTML template Tag](https://www.geeksforgeeks.org/html-template-tag/)
197198

198199
- [Document: importNode() method](https://developer.mozilla.org/en-US/docs/Web/API/Document/importNode)
200+
201+
## Loading Script Dynamically
202+
203+
Loading JavaScript dynamically in a web page can be useful for a variety of reasons, such as improving performance by only loading the necessary code when it's needed, or adding functionality to the page without requiring a full page reload.
204+
205+
It can be accomplished by creating a new `script` element, setting its `src` attribute to the URL of the JavaScript file, and then adding the element to the `head` section of the current HTML document. Here's an example:
206+
207+
```javascript
208+
const script = document.createElement('script');
209+
script.src = 'path/to/script.js';
210+
document.head.appendChild(script);
211+
```
212+
213+
In this example, `document.createElement('script')` creates a new `script` element. Then, we set the `src` attribute of the script element to the URL of the JavaScript file we want to load. Finally, we append the `script` element to the `head` section of the current document using `document.head.appendChild(script)`.
214+
215+
It's important to note that when you dynamically load a script, it's not guaranteed to execute immediately, and any code that depends on the loaded script should be executed only after the script has been fully loaded and is ready to use (it can also be handled with [`defer`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) attribute). To handle this, you can listen for the `load` event on the `script` element before executing any dependent code:
216+
217+
```javascript
218+
const script = document.createElement('script');
219+
script.src = 'path/to/script.js';
220+
script.addEventListener('load', () => {
221+
// Code that depends on the loaded script goes here
222+
});
223+
document.head.appendChild(script);
224+
```
225+
226+
In this example, we add an event listener for the `load` event on the `script` element. Once the script has loaded, the listener function will be executed, and any dependent code can be executed inside it.
227+
228+
229+
> **Note**
230+
>
231+
> Adding scripts dynamically can be a powerful feature, but it's important to use it carefully. If you're dynamically rendering user-created scripts, you need to be especially cautious, as this could make your website vulnerable to attacks like cross-site scripting. This type of attack involves injecting malicious code into your website's code, and we'll be discussing it in more detail in the security section later in the course. To avoid these kinds of attacks, it's crucial that you don't dynamically add a script based on user-entered content, or if you must do so, be sure to validate and sanitize the content thoroughly before executing it.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
console.log("Starting some analysis...")

Advanced-DOM-APIs/project_planner/assets/scripts/app.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,15 @@ class App {
158158
const finishedProjectsList = new ProjectList('finished');
159159
activeProjectsList.setSwitchHandlerFunction(finishedProjectsList.addProject.bind(finishedProjectsList));
160160
finishedProjectsList.setSwitchHandlerFunction(activeProjectsList.addProject.bind(activeProjectsList));
161+
document.getElementById('start-analytics').addEventListener('click', this.startAnalytics);
162+
}
163+
164+
// This is just a random function to demonstrate about adding a JS dynamically on some event
165+
static startAnalytics() {
166+
const analyticsScript = document.createElement('script');
167+
analyticsScript.src = 'assets/scripts/analytics.js';
168+
analyticsScript.defer = true;
169+
document.head.append(analyticsScript);
161170
}
162171
}
163172

Advanced-DOM-APIs/project_planner/index.html

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,5 +64,10 @@ <h2>Book Hotel</h2>
6464
</li>
6565
</ul>
6666
</section>
67+
<footer>
68+
<button id="start-analytics">
69+
Start Analytics!
70+
</button>
71+
</footer>
6772
</body>
6873
</html>

0 commit comments

Comments
 (0)