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

How to dynamically load js file using jQuery

Today I'm going to talk about how you can dynamically load a JavaScript file using jQuery.

To increase the performance of your website and reduce the total file size return, you can consider loading JavaSript files if necessary. Plus, it's super easy! Here's what you need to do.

In jQuery, you can use the $.getScript function to dynamically load a JavaScript file at runtime.

  1. First, create a JavaScript file that you want loaded dynamically. In our case, we have a js file :
    https://app.3schools.in/js/example.js
  2. Then use jQuery’s getScript() function like the following example. The first argument is obviously the URL of our external JavaScript file we want loaded into our page.
    $.getScript('https://app.3schools.in/js/example.js')
  3. Finally, include an optional callback function as an argument for when loading has finished successfully.
    $.getScript('https://app.3schools.in/js/example.js',function(){
      // success
    })

And there it is - now look at our final code. First, you need load our JavaScript file and then, click on the "Click Me" button to access our js file.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

<p>Load JavaScript file & then click the Click Me button.</p>
<button id="load-btn">Load Js File</button>
<button id="alert-btn">Click Me</button>

<script> 
 $("#load-btn").click(function(){ 
   $.getScript('https://app.3schools.in/js/example.js', function() {
      $("p").html('Javascript file is loaded!');
   });
 });
 $("#alert-btn").click(function(){
   example();
 });
</script>
save
listen
AI Answer
1 Answer
Write Your Answer
  1. To load a JavaScript file dynamically, you don't need to use jQuery library.

       1. Create a script element.
       2. Set the src and type attributes.
       3. Append the script element to the body.

    Here is my code.

    <script>
    let myScript = document.createElement("script");
      myScript.setAttribute("src", "https://app.3schools.in/js/example.js");
    document.body.appendChild(myScript);
    </script>


    Reply Delete
    Share
loading
back
View All