JavaScript File: JScript.js
function Helloworld() {
$(document).ready(function () {
$.ajax
({
type: "POST",
url: "Default.aspx/Helloworld",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
document.getElementById('textbox').value = msg.d;
}
})
});
}
Default.aspx
<head runat="server">
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
//This section works fine when uncommented
<%-- <script src="JScript.js" type="text/javascript"></script>--%>
<script type="text/javascript" language="javascript">
(function () {
var load = document.createElement('script');
load.type = 'text/javascript';
load.src = 'JScript.js';
load.async = true;
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body') [0]).appendChild(load);
})();
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="input" id="textbox" />
</form>
</body>
Code-Behind: Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "KeyHelloworld", "<script type='text/javascript'>Helloworld()</script>");
}
[WebMethod(EnableSession = true)]
public static string Helloworld()
{
return "Hello World";
}
I am attempting to asynchronously load a JavaScript file into a page, but the function is not executing. The above is the complete code to load the JavaScript file asynchronously.