加载时未调用 JavaScript 函数

标签 javascript

我正在使用一个 javascript 函数,该函数应该在页面加载完成时调用(如 JQuery 的函数) 这是它的样子:

<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;

}

当我在模型的分配处设置断点时,我们就命中了它。但是,没有发生任何其他事情(包括警报框。我不确定为什么它在加载时没有完全执行该函数。

最佳答案

这有效:

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");
});

关于加载时未调用 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39232338/

相关文章:

javascript - 尝试通过 Web API 创建记录时出现“未声明的属性”

javascript - 我怎样才能使 go Time 与 js Date 兼容

javascript - 如何构建 MongoDB 查询以使用 ACL 评估允许和拒绝的权限链?

javascript - 我希望 data.js 文件在其自己的代码中读取 data.js?key=123 作为 key = 123 。以便 data.js 文件将根据提供的 key 工作

javascript - 我怎样才能得到正确的输出?

javascript - 为什么通过 javascript 发送多个打印被 firefox 阻止以及如何禁用它?

javascript - 如何检查具有自定义属性的所有输入

javascript - 为什么大多数 JavaScript 原生函数都比它们的原始实现慢?

javascript - 如何使用 KARMA 对 React JSX ES6 代码进行单元测试?

javascript - 单击按钮时更改 div 的内容