在调用 ajax 启动长时间运行的任务之前,我需要完全渲染一个屏幕。 IE。在加载报告之前加载布局需要 10 秒以上(依赖于 Web 服务)。
我可以通过向页面添加一个单独的脚本并在加载该脚本时调用 Ajax 来实现此目的,但这是最好的设计吗?例如
_myreport.js:
$( document ).ready(function() {
var report = {
load: function() {
//test for report-container and run Ajax load if it exists
}
}
report.load();
});
我可能有几个页面用于此目的,并且我不太喜欢为多个不同页面使用多个脚本。或者,当可能需要也可能不需要 Ajax 调用(并且容器可能存在也可能不存在)时,我可能希望在多个页面上重复使用脚本。我可以在运行 Ajax 之前检查容器是否存在,但对我来说这感觉不是一个好的设计。我想在需要时调用它,而不是在每次页面加载时调用它,然后通过现有容器测试它是否适用。
我尝试在容器后面对主体中的函数进行一次小调用,但这会导致错误,因为 report.load()
函数尚未定义:
模板.phtml
<div id='report-container'></div>
<script>
$( document ).ready(function() {
report.load();
});
</script>
我可以在多个应用程序中重复使用的通用/标准且简洁的方法是什么?
最佳答案
report.load 尚未定义,因为它在 $( document ).ready 中变形。 您尝试在报告容器加载之后但在整个 DOM 加载之前调用它。 如果你在 $( document ).ready 之外声明你的 ajax 加载函数,它将是可用的。 与对它的调用相同,您在 div 加载后运行一个脚本,但因为它包含在 $.ready 中,所以它不会立即执行,而是等待其余部分加载... 像这样的东西应该可以工作
// not wrapped in $( document ).ready
var report = {
load: function() {
// not sure if you need to test for container, this function is called after it loads
//run Ajax
}
}
<div id='report-container'></div>
<script>
// not wrapped in $( document ).ready
report.load();
</script>
关于javascript - 在初始页面加载时通过 Ajax 加载内容的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26170263/