加载时不调用JavaScript函数

时间:2016-08-30 16:07:09

标签: javascript

我正在使用一个应该在页面加载完成时调用的javascript函数(比如JQuery' s函数) 看来它是什么样的:

<script>
var ready = function(fn) {

    // Sanity check
    if (typeof fn !== 'function') return;

    // If document is already loaded, run method
    if (document.readyState === 'complete') {
        return fn();
    }

    // Otherwise, wait until document is loaded
    // The document has finished loading and the document has been parsed but sub-resources such as images, 
    //stylesheets and frames are still loading. The state indicates that the DOMContentLoaded event has been fired.
    document.addEventListener('complete', fn, false);
};

ready(function() {
    alert(lang);
    Load(@Model.Language); //<--this is what I want called

    });
</script>

------->MVC Stuff<-------

 function Load(lang) {


 switch (lang) {
   case 'Other':
        BuildBox("text/text");
    case 'CSharp':
        BuildBox("text/x-csharp");
        break;

}

当我从模型中的Assignment设置断点时,我们正在点击它。然而,没有其他任何事情发生(包括警报框。我不确定为什么它没有在加载时完全执行该功能。

2 个答案:

答案 0 :(得分:0)

这有效:

function ready(fn) {

  // Sanity check
  if (typeof fn !== 'function') return;

  // If document is already loaded, run method
  if (document.readyState === 'complete') {
    fn();
  }

  // Otherwise, wait until document is loaded
  // The document has finished loading and the document has been parsed but sub-resources such as images, 
  //stylesheets and frames are still loading. The state indicates that the DOMContentLoaded event has been fired.
  document.addEventListener('readystatechange', function () {
    if (this.readyState === 'complete') fn();
  }, false);
}

ready(function() {
  alert("loading complete");
});

答案 1 :(得分:0)

我建议你使用它。

    (function () {
    var x = "Hello!!";      // I will invoke        myself
})();

parantheses();在匿名函数调用函数本身之后。 你可以像这样恭维文件就绪事件。

    document.addEventListener('DOMContentLoaded', function() {
   // ...
});