JavaScript

How to Load and Execute JS Files Using Ajax Requests (Asynchronous Communication)

In this article, I will introduce a method to load and execute JavaScript code contained in separate JS files using the $.ajax() function for asynchronous communication.

JavaScript Code to Load and Execute JS Files Using Ajax Requests

* The JS files to be loaded are ajax1.js and ajax2.js.
(The character encoding of the JS files is set to UTF-8)
Include the jQuery file and load the JS files using $.ajax() upon clicking the areas #idAj01 and #idAj02.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){

	$("#idAj01").click(function(){
		// Load ajax1.js
		$.ajax({
			type: "GET",
			url: "ajax1.js",
			dataType: "script"
		});
	});
	
	$("#idAj02").click(function(){
		// Load ajax2.js
		$.ajax({
			type: "GET",
			url: "ajax2.js",
			dataType: "script"
		});
	});

});
</script>

CSS for Buttons Executing Ajax Requests (Loading JS Files)

* Adjust as needed.

<style type="text/css">
<!--
body{
	margin:0;
	padding:0;
}
h1{
	font-size:16px;
	font-weight:normal;
	line-height:2.0em;
	text-align:center;
	padding:15px 0;
}
#idWrap{
	width:700px;
	margin:0 auto;
	text-align:center;
}
#idAj01{
	padding:10px;
	background-color:#FFFF66;
	width:200px;
	margin:0 auto;
	cursor:pointer;
}
#idAj01:hover{
	background-color:#FFFFCC;
}
#idAj02{
	padding:10px;
	background-color:#FF99FF;
	width:200px;
	margin:0 auto;
	cursor:pointer;
}
#idAj02:hover{
	background-color:#FFCCFF;
}
-->
</style>

HTML Example for Buttons Executing Ajax Requests (Loading JS Files)

* Click the areas with id=”idAj01″ or id=”idAj02″ to load the JS files ajax1.js or ajax2.js and execute the JavaScript code within them. Adjust as needed.

<div id="idWrap">
    <h1>Click the following areas (yellow, pink) to load the JS files<br />
    <a href="ajax1.js" target="_blank">ajax1.js</a>と<a href="ajax2.js" target="_blank">ajax2.js</a>using Ajax requests (asynchronous communication) and execute the loaded JavaScript.</h1>
    
    <div id="idAj01">Load ajax1.js</div>
    <br />
    <br />
    <div id="idAj02">Load ajax2.js</div>
    
</div><!--/idWrap-->

Demo Page for Loading and Executing JS Files Using Ajax Requests

Demo Page for Loading and Executing JS Files Using Ajax Requests

Ajax (asynchronous communication) can also be used to load XML or PHP files, among other possibilities.

 
・Use at your own risk.
 Please do not reuse the Google Analytics tags in the demo page.