chr*_*ris 1244 html javascript jquery
好吧,这可能只是一个愚蠢的问题,但我确信还有很多其他人不时会问同样的问题.我,我只是想以任何方式100%确定.有了jQuery,我们都知道这很精彩
$('document').ready(function(){});
Run Code Online (Sandbox Code Playgroud)
但是,假设我想运行一个用标准JavaScript编写的函数,没有库支持它,并且我想在页面准备好处理它时立即启动一个函数.什么是正确的方法来解决这个问题?
我知道我能做到:
window.onload="myFunction()";
Run Code Online (Sandbox Code Playgroud)
......或者我可以使用body标签:
<body onload="myFunction()">
Run Code Online (Sandbox Code Playgroud)
...或者我甚至可以在所有内容之后尝试在页面底部,但结尾body或html标记如:
<script type="text/javascript">
myFunction();
</script>
Run Code Online (Sandbox Code Playgroud)
什么是以jQuery方式发布一个或多个函数的跨浏览器(旧/新)兼容方法$.ready()?
jfr*_*d00 1774
在没有为您提供所有跨浏览器兼容性的框架的情况下,最简单的方法就是在正文末尾调用代码.这比onload处理程序执行起来更快,因为它只等待DOM准备就绪,而不是所有图像都要加载.而且,这适用于每个浏览器.
<!doctype html>
<html>
<head>
</head>
<body>
Your HTML here
<script>
// self executing function here
(function() {
// your page initialization code here
// the DOM will be available here
})();
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
如果你真的不想这样做,并且你需要跨浏览器兼容性而你不想等待$(document).ready(),那么你可能应该去看看像jQuery这样的框架如何实现它的window.onload方法.根据浏览器的功能,它相当复杂.
为了让您了解jQuery的功能(在脚本标记放置的任何位置都可以使用).
如果支持,它会尝试标准:
function docReady(fn) {
// see if DOM is already available
if (document.readyState === "complete" || document.readyState === "interactive") {
// call on next available tick
setTimeout(fn, 1);
} else {
document.addEventListener("DOMContentLoaded", fn);
}
}
Run Code Online (Sandbox Code Playgroud)
回落:
docReady(function() {
// DOM is loaded and ready for manipulation here
});
Run Code Online (Sandbox Code Playgroud)
或者对于旧版本的IE,它使用:
document.addEventListener('DOMContentLoaded', fn, false);
Run Code Online (Sandbox Code Playgroud)
回落:
window.addEventListener('load', fn, false )
Run Code Online (Sandbox Code Playgroud)
并且,在IE代码路径中有一些我没有完全遵循的解决方法,但看起来它与帧有关.
这是$(document).ready()用简单的javascript编写的jQuery的完全替代品:
document.attachEvent("onreadystatechange", fn);
Run Code Online (Sandbox Code Playgroud)
最新版本的代码在GitHub上公开共享,网址为https://github.com/jfriend00/docReady
用法:
window.attachEvent("onload", fn);
Run Code Online (Sandbox Code Playgroud)
这已经过测试:
(function(funcName, baseObj) {
// The public function name defaults to window.docReady
// but you can pass in your own object and own function name and those will be used
// if you want to put them in a different namespace
funcName = funcName || "docReady";
baseObj = baseObj || window;
var readyList = [];
var readyFired = false;
var readyEventHandlersInstalled = false;
// call this when the document is ready
// this function protects itself against being called more than once
function ready() {
if (!readyFired) {
// this must be set to true before we start calling callbacks
readyFired = true;
for (var i = 0; i < readyList.length; i++) {
// if a callback here happens to add new ready handlers,
// the docReady() function will see that it already fired
// and will schedule the callback to run right after
// this event loop finishes so all handlers will still execute
// in order and no new ones will be added to the readyList
// while we are processing the list
readyList[i].fn.call(window, readyList[i].ctx);
}
// allow any closures held by these functions to free
readyList = [];
}
}
function readyStateChange() {
if ( document.readyState === "complete" ) {
ready();
}
}
// This is the one public interface
// docReady(fn, context);
// the context argument is optional - if present, it will be passed
// as an argument to the callback
baseObj[funcName] = function(callback, context) {
if (typeof callback !== "function") {
throw new TypeError("callback for docReady(fn) must be a function");
}
// if ready has already fired, then just schedule the callback
// to fire asynchronously, but right away
if (readyFired) {
setTimeout(function() {callback(context);}, 1);
return;
} else {
// add the function and context to the list
readyList.push({fn: callback, ctx: context});
}
// if document already ready to go, schedule the ready function to run
if (document.readyState === "complete") {
setTimeout(ready, 1);
} else if (!readyEventHandlersInstalled) {
// otherwise if we don't have event handlers installed, install them
if (document.addEventListener) {
// first choice is DOMContentLoaded event
document.addEventListener("DOMContentLoaded", ready, false);
// backup is window load event
window.addEventListener("load", ready, false);
} else {
// must be IE
document.attachEvent("onreadystatechange", readyStateChange);
window.attachEvent("onload", ready);
}
readyEventHandlersInstalled = true;
}
}
})("docReady", window);
Run Code Online (Sandbox Code Playgroud)
工作实施和试验台:http://jsfiddle.net/jfriend00/YfD3C/
以下是其工作原理的摘要:
.ready()docReady(fn, context)被调用时,检查是否准备好处理程序已经被解雇.如果是这样,只需在JS的这个线程结束后安排新添加的回调docReady(fn, context).setTimeout(fn, 1)存在,则使用document.addEventListenerfor .addEventListener()和"DOMContentLoaded"events 安装事件处理程序."加载"是安全的备份事件,不应该需要."load"不存在,则使用document.addEventListenerfor .attachEvent()和"onreadystatechange"events 安装事件处理程序."onload"下,检查是否onreadystatechange,如果是,则调用函数来触发所有就绪处理程序.注册的处理程序document.readyState === "complete"保证按其注册顺序被解雇.
如果docReady()在文档准备就绪后调用,则将在当前执行线程完成后立即执行回调计划docReady(fn).这允许调用代码总是假设它们是稍后将调用的异步回调,即使稍后在JS的当前线程完成并且它保留调用顺序之后.
Ram*_*tra 148
我想在这里提到一些可能的方法以及适用于所有浏览器的纯javascript技巧:
// with jQuery
$(document).ready(function(){ /* ... */ });
// shorter jQuery version
$(function(){ /* ... */ });
// without jQuery (doesn't work in older IEs)
document.addEventListener('DOMContentLoaded', function(){
// your code goes here
}, false);
// and here's the trick (works everywhere)
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
// use like
r(function(){
alert('DOM Ready!');
});
Run Code Online (Sandbox Code Playgroud)
正如原作者所解释的,这里的技巧是我们正在检查document.readyState属性.如果它包含字符串in(在uninitialized和中loading,前5 个中的前两个DOM就绪状态),我们设置超时并再次检查.否则,我们执行传递的函数.
这里是适用于所有浏览器的技巧的jsFiddle .
感谢Tutorialzine将其纳入本书.
Tom*_*kel 135
如果您正在使用没有jQuery的VANILLA普通JavaScript,那么您必须使用(Internet Explorer 9或更高版本):
document.addEventListener("DOMContentLoaded", function(event) {
// Your code to run since DOM is loaded and ready
});
Run Code Online (Sandbox Code Playgroud)
以上是jQuery的等价物.ready:
$(document).ready(function() {
console.log("Ready!");
});
Run Code Online (Sandbox Code Playgroud)
这也可以写成速记这样,这jQuery将就绪后运行,即使发生.
$(function() {
console.log("ready!");
});
Run Code Online (Sandbox Code Playgroud)
不要与下面的混淆(这不是为DOM做好准备):
不要使用像这样自行执行的IIFE:
Example:
(function() {
// Your page initialization code here - WRONG
// The DOM will be available here - WRONG
})();
Run Code Online (Sandbox Code Playgroud)
此IIFE不会等待您的DOM加载.(我甚至在谈论最新版的Chrome浏览器!)
Phi*_*ilT 78
在IE9中测试过,最新的Firefox和Chrome也在IE8中得到了支持.
document.onreadystatechange = function () {
var state = document.readyState;
if (state == 'interactive') {
init();
} else if (state == 'complete') {
initOnCompleteLoad();
}
}?;
Run Code Online (Sandbox Code Playgroud)
示例:http://jsfiddle.net/electricvisions/Jacck/
更新 - 可重复使用的版本
我刚开发了以下内容.这是一个相当简单的等效于jQuery或Dom准备就绪,没有向后兼容性.它可能需要进一步完善.测试了最新版本的Chrome,Firefox和IE(10/11),并且应该在旧版浏览器中使用.如果发现任何问题,我会更新.
window.readyHandlers = [];
window.ready = function ready(handler) {
window.readyHandlers.push(handler);
handleState();
};
window.handleState = function handleState () {
if (['interactive', 'complete'].indexOf(document.readyState) > -1) {
while(window.readyHandlers.length > 0) {
(window.readyHandlers.shift())();
}
}
};
document.onreadystatechange = window.handleState;
Run Code Online (Sandbox Code Playgroud)
用法:
ready(function () {
// your code here
});
Run Code Online (Sandbox Code Playgroud)
它是为处理JS的异步加载而编写的,但您可能希望首先同步加载此脚本,除非您正在缩小.我发现它在开发中很有用.
现代浏览器还支持脚本的异步加载,这进一步增强了体验.支持异步意味着可以在呈现页面的同时同时下载多个脚本.根据异步加载的其他脚本或使用minifier或类似browserify来处理依赖项时,请注意.
Lor*_*ill 19
HubSpot的好人有一个资源,你可以找到纯Javascript方法来实现很多jQuery的优点 - 包括 ready
http://youmightnotneedjquery.com/#ready
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', fn);
} else {
document.attachEvent('onreadystatechange', function() {
if (document.readyState != 'loading')
fn();
});
}
}
Run Code Online (Sandbox Code Playgroud)
示例内联用法:
ready(function() { alert('hello'); });
Run Code Online (Sandbox Code Playgroud)
我不确定您要问的是什么,但这可能会有所帮助:
window.onload = function(){
// Code. . .
}
Run Code Online (Sandbox Code Playgroud)
要么:
window.onload = main;
function main(){
// Code. . .
}
Run Code Online (Sandbox Code Playgroud)
您的方法(在关闭正文标记之前放置脚本)
<script>
myFunction()
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
是支持新旧浏览器的可靠方式.
function ready(fn){var d=document;(d.readyState=='loading')?d.addEventListener('DOMContentLoaded',fn):fn();}
Run Code Online (Sandbox Code Playgroud)
使用方式
ready(function(){
//some code
});
Run Code Online (Sandbox Code Playgroud)
(function(fn){var d=document;(d.readyState=='loading')?d.addEventListener('DOMContentLoaded',fn):fn();})(function(){
//Some Code here
//DOM is avaliable
//var h1s = document.querySelector("h1");
});
Run Code Online (Sandbox Code Playgroud)
支持:IE9 +
| 归档时间: |
|
| 查看次数: |
1289145 次 |
| 最近记录: |