Gihan
Gihan

Reputation: 3749

How Can I Load Multiple Scripts After a Page Has Loaded?

I am using following code inside my HTML to load a JS file after page load.(DOMContentLoaded)

<script>
document.addEventListener('DOMContentLoaded', function() {
  var script = document.createElement('script');
  script.src = 'https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.12.4.min.js';
  document.getElementsByTagName('body')[0].appendChild(script);
});
</script>

But I got several scripts to load and I have no idea how to implement this for multiple scripts.

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.12.4.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/4.0.0/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@8"></script>

Your help with this would be greatly appreciated. Thanks.

Upvotes: 5

Views: 936

Answers (1)

nrayburn-tech
nrayburn-tech

Reputation: 968

As mentioned in the comments, you could look at using a module loader.

If you want to do it without a module loader, then you have the right idea. To keep the code easier to read/shorter, you could create an array of urls and iterate through them and appending a new script element for each.

    const jsFiles = [
        'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js',
        'https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.12.4.min.js',
        'https://ajax.aspnetcdn.com/ajax/bootstrap/4.0.0/bootstrap.min.js',
        'https://cdn.jsdelivr.net/npm/sweetalert2@8'
    ]
    jsFiles.forEach((item) => {
        const scriptEle = document.createElement('script');
        scriptEle.src = item;
        document.head.appendChild(scriptEle);
    })

Upvotes: 4

Related Questions