页面完全渲染后加载 JavaScript
我已将 JavaScript 代码添加到我的 Drupal 7 主题中,但它无法按预期运行,因为当我的函数被触发时,CSS 未正确应用。
所以我尝试了一个最小的实现来检查发生了什么。
jQuery(document).ready(function($) {
alert("Start");
}
alert()
在页面完全加载之前触发(即所有标题都丢失)。 我怎样才能防止这种情况发生?
I've added JavaScript code to my Drupal 7 theme, but it fail to run as it's expected because css are not properly applied when my function is fired.
So I've tried a minimal implementation to check what's happening.
jQuery(document).ready(function($) {
alert("Start");
}
alert()
is fired before the page is fully loaded (i.e. all titles are missing).
How can I prevent this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了在所有内容完全加载后执行脚本,您需要:
jQuery.ready() 在 DOM 准备好后立即执行,这通常是在加载外部资源之前。
In order execute a script after everything has fully loaded you want:
jQuery.ready() executes as soon as the DOM is ready, which is usually before external resources have loaded.
此处了解 Drupal 7 JavaScript API。您需要注意行为部分。行为与您在示例中尝试执行的操作相同,但是,当加载 Drupal 页面时,它所做的第一件事就是实例化
Drupal
对象。该对象由具有行为和属性的每个模块扩展。当您在文档上使用 Drupal 行为而不是标准 JQuery 时,您可以在 JavaScript 函数中访问其他模块定义的所有属性和方法。这些教程 (1、2)适用于 Drupal 6,但它们给了你一个很好的解释了解 Drupal 行为是什么。
Read about the Drupal 7 JavaScript API here. You want to give attention to the behaviors section. Behaviors do the same thing you are trying to make in your example, however, when a Drupal page loads, one of the first things it does is instantiate the
Drupal
object. This object gets extended by every module with behaviors and attributes. When you use Drupal behaviors instead of the standard JQuery on document ready you have accessible in your JavaScript function all the properties and methods defined by other modules.These tutorials (1, 2) are for Drupal 6, but they give you a good explanation and idea of what Drupal behaviors are.