调用外部jQuery函数w/o document.ready();

问题描述:

有点新来jQuery和寻找帮助如何将所有我的脚本保存在一个外部文件中,而不是全部嵌套在document.ready();.我希望只能从特定页面调用某些函数,其余部分则使用ready();来处理。我不是100%确定从页面调用函数的最佳做法是什么:/ 谢谢。调用外部jQuery函数w/o document.ready();

+0

我不确定你的意思。当DOM准备就绪时,你可以做任何事情。和? – karim79 2010-12-01 01:24:00

有多个document.readys没有错误

我喜欢为每个页面添加一个唯一的ID,并且在执行前检查该ID是否存在。您可以创建一个简单的包装功能,做检查和的document.ready等待:

var pageReady = function (id, callback) { 
    $(function() { 
     if ($(id).length) { 
     callback(); 
     } 
    }); 
}; 

随后,类似的document.ready,你可以有:

pageReady("#home-page", function() { 
    // Code will only run for home page here 
}); 

pageReady("#search-page", function() { 
    // Code will only run for search page here 
}); 

记得刚加入的ID ...

<body id="home-page"> 

您可以使用多个dom readys。

我最喜欢的方式来确定是否在一个页面是给身体各式独特的I类应该运行一些代码,然后用这个...

if ($('body').hasClass('contact')) { 
    // Validate form, etc 
} 

虽然JavaScript提供加载事件在呈现页面时执行代码,直到所有资源(如图像)都已完全接收后才会触发此事件。在大多数情况下,脚本可以在DOM层次结构完全构建后立即运行。传递给.ready()的处理程序保证在DOM准备就绪后执行,因此这通常是附加所有其他事件处理程序并运行其他jQuery代码的最佳位置。在使用依赖CSS样式属性值的脚本时,在引用脚本之前引用外部样式表或嵌入样式元素很重要。

http://api.jquery.com/ready/

在外部文件中,可以有$(document).ready(function() { //code here; });另外,你可以把所有的功能在外部文件,然后只需您的网页上已经

$(document).ready(function() { myfunction(); }); 
+0

Aww,感谢编辑 – Prescott 2010-12-01 01:52:19

你可以把你的所有如果你喜欢,可以在单个文件中使用脚本如果您不需要操作DOM或与DOM进行交互,那么您可以在文件中使用普通的JS函数,而不使用document.ready()函数。然后,您可以将所有DOM操作和交互JS放入document.ready()函数中。您还可以将JS放入$(window).load()函数中,以便在所有资源加载到包含图像的页面上后运行代码。

例子:

$(window).load(function() { 
    // code that will run once all resources and the DOM are loaded into the browser 
    console.log("window loaded"); 
}); 

runOnScriptLoad(); 
function runOnScriptLoad() { 
    // code that will run as soon as the JS file loads 
    console.log("script loaded"); 
} 

$(document).ready(function() { 
    // code that will run once the entire DOM is loaded into the browser 
    console.log("DOM ready"); 
}); 

$(window).load(function() { 
    // code that will run once all resources and the DOM are loaded into the browser 
    console.log("window loaded"); 
}); 

示例页面: =>http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-dom-ready.html

让你的萤火控制台时打开加载页面,你会看到在每一个得到执行的顺序。

+0

+1,我喜欢用`$(窗口)。load()` – Alex 2010-12-01 02:05:19

+0

@Alex为什么?只有特定的情况下这是有用的,因为它比文档准备好慢。 – 2010-12-01 04:11:03