ArticleZip > Dynamically Loading Css File Using Javascript With Callback Without Jquery

Dynamically Loading Css File Using Javascript With Callback Without Jquery

When it comes to web development, dynamically loading CSS files using JavaScript can be a handy trick to enhance the performance and flexibility of your website. In this article, we'll walk you through the process of dynamically loading a CSS file using pure JavaScript, without relying on jQuery. Additionally, we'll show you how to implement a callback function to ensure seamless execution.

To begin, let's create a new JavaScript function that will handle the loading of the CSS file. This function will accept the CSS file's URL as a parameter along with an optional callback function. Here's a simple example to get you started:

Javascript

function loadCSS(url, callback) {
  var link = document.createElement('link');
  link.rel = 'stylesheet';
  link.href = url;
  
  document.head.appendChild(link);
  
  if (callback && typeof callback === 'function') {
    link.onload = callback;
  }
}

In the above function, we first create a new `` element and set its `rel` attribute to 'stylesheet' and the `href` attribute to the provided CSS file URL. We then append this `` element to the `` section of the document.

Next, we check if a callback function has been provided and if it is indeed a function. If both conditions are met, we set the `onload` event of the `` element to the provided callback function. This ensures that the callback is executed once the CSS file has finished loading.

Now, let's see how you can use this `loadCSS` function in your code. Suppose you have a button on your webpage, and you want to load a CSS file dynamically when this button is clicked. Here's how you can achieve this:

Javascript

document.querySelector('#load-css-btn').addEventListener('click', function() {
  loadCSS('path/to/your/styles.css', function() {
    console.log('CSS file loaded successfully!');
    // Place any additional code that needs to run after the CSS file has loaded here
  });
});

In the above code snippet, we first select the button element with the ID of 'load-css-btn'. We then attach an event listener to this button that listens for a 'click' event. When the button is clicked, the `loadCSS` function is called with the URL of your CSS file and a callback function.

The callback function here simply logs a message to the console once the CSS file has finished loading. You can customize this callback function to perform any additional tasks that rely on the CSS file being fully loaded.

By dynamically loading CSS files using pure JavaScript, you can optimize your website's performance and improve the overall user experience. This approach also allows for more flexibility and control compared to traditional methods. Give it a try in your projects and see the difference it makes!

×