JavaScript is used to add dynamic features and change content on web pages, and sometimes you may need to load and execute external JS files. Especially in large web applications or sites, it is common to manage JavaScript as external files and load them as needed, rather than writing all JavaScript within a single page.
This article explains in detail how to load external JS files using jQuery’s .getScript method.
What is jQuery’s .getScript?
jQuery’s .getScript() is a method to asynchronously load and execute external JavaScript files. By using this method, you can load JavaScript only when needed without slowing down the page loading speed.
Basic CSS Settings
Below are the basic CSS settings for the demo page. These settings are for the purpose of verifying the operation of the external JS file, so please modify them as needed.
<style type="text/css">
<!--
body {
font-family:Verdana,"Hiragino Kaku Gothic Pro","ヒラギノ角ゴ Pro W6",Osaka,"MS Pゴシック",Arial,sans-serif;
margin:0;
padding:0;
}
h1{
font-size:16px;
font-weight:normal;
line-height:1.4em;
text-align:center;
padding:15px 0;
}
#idWrap{
width:800px;
margin:0 auto;
}
-->
</style>
Loading External JS Files Using .getScript()
Next, I will show you how to load external JS files using the $.getScript() method. Here, I am using jQuery version 1.8 series.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
window.onload = (function(){
$.getScript("https://dad-union.com/demo/js/20140418-getscript-external-file-crossdomain/ext.js");
});
</script>
Example of External JS File
Below is a simple example of the external JS file (ext.js) to be loaded. This example displays an alert message to confirm that the JS file has been loaded correctly.
alert("The external JS file ‘ext.js’ has been loaded.");
Demo Page to Execute External JS File Processing Using jQuery’s .getScript
For those who want to check the actual operation, please see the demo page below.
Demo to execute external JS file processing using jQuery’s .getScript
Cross-Domain and jQuery’s .getScript
Typically, cross-domain communication in JavaScript is restricted for security reasons. However, recent versions of jQuery allow the use of .getScript across domains. However, actual cross-domain operation needs to be confirmed, so I plan to take it on as a future experiment.
In Conclusion
This was an explanation of how to load external JS files using jQuery’s .getScript. By using this method, you can make your web page operations more flexible and improve user experience.
Please use at your own risk. Do not use the Google Analytics tag within the demo page tags.