简体   繁体   中英

How Can I Load Multiple Scripts After 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.as.netcdn.com/ajax/jquery/jquery-1.12.4.min.js"></script> <script src="https://ajax.as.netcdn.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.

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);
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM