end video

This lesson is only accessible in the paid version of the course.

Get access to all lessons 💫 price: 34.99$

If you already have an account click here.

Do you speak JavaScript?

§ Loading resources dynamically

It's funny how in the past we had to write a lot of things alone. There was no NPM or GitHub. We had to write our own loaders. Utilities that load JavaScript files or CSS files. Today this problem is solved by numerous packages, but I figured it will be interesting to share.

Here's how we can load JavaScript, CSS and an image dynamically:

const script = document.createElement('script');
script.src = './logic.js';
script.async = true;
script.type = 'text/javascript';
script.addEventListener('load', () => {
  console.log('JavaScript file is loaded');
});
document.querySelector('head').append(script);

const style = document.createElement('link');
style.href = './styles.css';
style.rel = 'stylesheet';
style.addEventListener('load', () => {
  console.log('CSS file is loaded');
});
document.querySelector('head').append(style);

const img = document.createElement('img');
img.src = './dog.jpg';
img.addEventListener('load', () => {
  console.log('Image file is loaded');
});
document.querySelector('body').append(img);

The idea is to create a DOM element, set proper attributes and attach it to the DOM tree.

questionnaire
discussion

Materials

Materials related to the lesson:
Files associated with the lesson

Materials

🌟 Congratulations! You successfully finished "Do you speak JavaScript?". 🌟