我想知道是否有办法仅在文档准备好时加载部分脚本,我的意思是当所有css、js和图像下载完毕后运行有点重的php脚本。
在 php 中我知道可以使用 if else 但在 jquery 上?
可以是:?
<script>
jQuery( document ).ready(function( $ ) {
</script>
<?php
$script = $this->getAllItems();
?>
<script>
});
</script>
<div class="page">
<?php echo $this->getChildHtml('header'); ?>
<div class="main-container col2-left-layout">
<div class="main container_16 clearfix">
<div class="col-main grid_16">
<?php echo $this->getChildHtml('top_callout'); ?>
</div>
<div class="col-main grid_16">
<?php echo $this->getChildHtml('breadcrumbs'); ?>
</div>
<div class="col-main grid_12">
<?php echo $this->getChildHtml('global_messages'); ?>
on document ready call content
<?php echo $this->getChildHtml('content'); ?>
</div>
<div class="col-left sidebar grid_4"><?php echo $this->getChildHtml('left'); ?></div>
</div>
</div>
<?php echo $this->getChildHtml('footer'); ?>
<?php echo $this->getChildHtml('before_body_end'); ?>
</div>
感谢任何帮助!
最佳答案
我认为存在语言困惑。 PHP 是一种服务器端语言。当原始源接触您的浏览器时,它已经运行并完成。另一方面,JavaScript 在浏览器中客户端进行解析和呈现。
如果您需要在页面加载后运行 PHP 脚本,则需要使用 AJAX。您必须执行以下操作:
$(window).load(function () {
$.ajax({
url: "some-php-script.php",
data: { ... } // data to send to php if applicable,
... // other options that may be needed
success: function (res) {
... // handle successful return of data (if applicable)
}
error: function (res) {
... // handle error if appropriate
}
});
});
引用: .ajax()
编辑:
由用户3553931建议
由于您想要等待所有样式表、脚本和图像加载,因此我更新了我的答案以使用 load
事件而不是 DOMContentLoaded
( $(document).ready
后面的事件。
根据下面的 MDN 文档,load
事件似乎比 DOMContentLoaded
事件更能满足您的问题要求。
引用: DOMContentLoaded
摘录:
The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).
关于php - 在准备好的 Jquery 文档上运行 php 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24213547/