
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.
- 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
- 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')
- 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
How to dynamically load js file using jQuery
1
Today I'm going to talk about how you can dynamically load a JavaScript file using jQ…
asked
Apu
1 answers
2915
Today I'm going to talk about how you can dynamically load a JavaScript file using jQ…
Answer Link
answered
Apu
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>