javascript如何检测函数的定义位置,顶部/底部?

时间:2015-04-20 13:09:17

标签: javascript jquery ajax

只要我将employee部分及其脚本作为index.html的一部分加载

,我就有以下代码正常工作

index.html Working Demo

<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" href="style.css" />
    <script data-require="jquery" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Employee Details loaded as usual and sript is executing able to see alert</h1>
  </body>

</html>

的script.js

var empModule = (function (empModule) {
    var Years = null;

    $(document).ready(function () {
        var empdata = { Name: 'Billa' }
        var myVM = new empModule.viewModel(empdata);

    });

    empModule.viewModel = function (data) {
        var that = this;
        that.Name = data.Name;
        alert(that.Name);
    };   

    return {
        empModule: empModule
    }
} (empModule || {}));            

错误情景:

我们决定根据某些条件移动员工相关部门。因此,我们通过Ajax加载此部分和部分相关的脚本(emp.js)。但现在它抛出了错误empModule.viewModel is not a constructor。为什么会这样?

如果我将document.ready部分移动到底部,如下面的顺序那样,它正在运行

Emp.js (从script.js移到emp.js并通过ajax加载(

var empModule = (function (empModule) {
var Years = null;
// Code not working when we load this script file using Ajax.            
// But works if we move this document.ready at bottom 
//$(document).ready(function () {
  //  var empdata = { Name: 'Billa' }
  //  var myVM = new empModule.viewModel(empdata);

//});
empModule.viewModel = function (data) {
    var that = this;
    that.Name = data.Name;
    alert(that.Name);
};
//Working only if I keep the ready section here
$(document).ready(function () {
    var empdata = { Name: 'Billa' }
    var myVM = new empModule.viewModel(empdata);

});

return {
    empModule: empModule
}
} (empModule || {})); 
  

函数empModule将自动执行   执行功能。当它执行时,它需要准备一个   empModule.viewModel对象,但在viewModel时未能这样做   定义位于document.ready(调用者)之后。这只会发生   当我通过Ajax加载此脚本时,但如果我在页面中加载它

,则可以正常工作

2 个答案:

答案 0 :(得分:1)

这是因为在第一个示例中,script.js是文档的一部分,因此document.ready在尝试调用empModule.viewModel()之前等待加载.js文件

在第二个示例中,您的脚本是异步加载的,但页面没有考虑到这一点。所以页面加载(没有script.js),然后加载脚本。 此时,文档已准备就绪(因为ajax加载的脚本不是文档的一部分),因此empModule.viewModel()调用会在脚本的其余部分之前立即触发(这是定义功能),你得到你的错误。

答案 1 :(得分:0)

就像@dougajmcdonald说的那样是你的问题,但你的解决方案是,而不是通过AJAX加载,只需在文档中插入脚本标记:

// Instead of $.ajax(... /myScript.js) use:

function loadMyScript(){
        var script = document.createElement("script");
        script.type  = "text/javascript";
        script.src   = 'myScript.js';
        script.onload = function() {                           
            empModule.doSomething(); // or callback
        };
}