jQuery getScript() Method

Last Updated:

jQuery getScript() Method

jQuery getScript() Method loads a JavaScript file from the server using a GET HTTP request, then execute it.

Note: Javascript file used in this example is alert-me.js.

Example

HTML Online Compiler
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery getScript() Method</h1> <button onclick="myFunction()">Click Me</button> <script> $(document).ready(function(){ $.getScript("/script/alert-me.js"); }); </script> </body> </html>

Syntax

$.getScript(url, success);

Parameter Values

Value Type Explanation
url Required Specifies the URL to which the request to be sent.
success Optional Specifies a callback function that is executed if the request succeeds.

Browser Support

Devicedesktopmobile
Browsergoogle chromesafarifirefoxinternet Exploreredgeoperagoogle chromesafarifirefoxedgeoperaandroid webviewsamsung internet
getScript()YesYesYesYesYesYesYesYesYesYesYesYesYes

jQuery getScript() Method with Callback

When requesting a large script file, you need to ensure whether the file is loaded completely before calling any function in it. Thus callback is necessary.

Example

HTML Online Compiler
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery getScript() Method</h1> <button onclick="myFunction()">Click Me</button> <script> $(document).ready(function(){ $.getScript("/script/alert-me.js") .done(function(script, textStatus) { console.log(textStatus); }); }); </script> </body> </html>

Share this Page

Meet the Author