如何异步加载包含ajax调用的javascript文件?

时间:2012-05-07 19:10:49

标签: javascript asp.net jquery

我有一个名为JScript.js的JavaScript文件,这个文件包含一个函数,即a-aax调用点网页

alert('jscript.js called');

function AddTag() {
var htag = document.getElementById("hdntag").value.split('|');
var texttag = document.getElementById("taginput").value;

for (i = 1; i < htag.length; i++) {
    var onetag = htag[i].split(',');

    if (onetag[0] == texttag) {
        alert("Already Exist!!!");
        return false;
    }
}
$(document).ready(function () {
    $.ajax
                           ({
                               type: "POST",
                               url: "Checked.aspx/AddTag",
                               data: "{'TagName': '" + $('#taginput').val() + "'}",
                               contentType: "application/json; charset=utf-8",
                               dataType: "json",
                               async: true,
                               cache: false,
                               success: function (msg) {
                                   document.getElementById("hdntag").value += '|' + texttag + ',' + msg.d;
                                   Makeedittabletaghtml();
                               }
                           })
});
document.getElementById("taginput").value = "";

}

我正在尝试将此JavaScript文件异步加载到页面中,但我只收到警告,即'jscript.js调用',但下面执行的函数是加载JavaScript文件的代码异步

 (function() {
    var dsq = document.createElement('script');
    dsq.type = 'text/javascript';
    dsq.src = 'JScript.js';
    dsq.async = true;
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();

但是当我将文件包含在页面中时,它会运行并执行正常的

<script type="text/javascript" src="JScript.js"></script>

2 个答案:

答案 0 :(得分:0)

您可以使用.getScript() jQuery函数执行此操作:

$.getScript("JScript.js", function(){
   alert("Script loaded and executed.");
   // here you can use anything you defined in the loaded script
});

答案 1 :(得分:0)

Farhan Ahmad已经回答了它,无论如何,document.ready只有在你加载页面并且dom准备就绪时才会触发,所以首先让你的JScript.js如下

alert('jscript.js called');

function AddTag() {...}

function myReadyFunc(){
    $.ajax({
    ...
    ...
    });
}

然后使用$.getScript加载文件并致电myReadyFunc(),这将调用ajax

$.getScript("JScript.js", function(){
    alert("Script loaded and executed.");
    myReadyFunc();
});

参考: Here.