Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu February 06, 2023 › #dynamically #HowTo

JavaScript load script from url

Today, I'm going to talk about how you can dynamically load a script from an URL using JavaScript.

This is a great way to add new features and functionality to your website. It also allows you to add content quickly and easily without having to manually include the code in your HTML page.

How to load script from url using JavaScript. #

So let's dive in and take a look at how this works with an example!

First, we'll need two things:
  1. The script that we want our page to load. In my case, I have an URL.
    https://app.3schools.in/js/example.js
  2. Where that script is located.

Suppose we want to access a function from the URL on our site, but only after you click on a link or button. We could use JavaScript's dynamic loading feature like this:

<button onclick="myFunc()">Load URL</button>
<script> 
   function myFunc(){ 
     let myScript = document.createElement('script');
     myScript.src = 'https://app.3schools.in/js/example.js';
     document.body.appendChild(myScript);     
     myScript.onload = function(){
        example();
     }
   }   
</script>    
  • Add button which will trigger above mentioned function when clicked by user.
  • Now, create the function.
  • Create a new script element/tag using the createElement() method.
  • Set its source attribute.
  • Append it into body so browser can download it when needed.
save
listen
AI Answer
Write Your Answer
loading
back
View All