我有一个使用$(document).ready的脚本,但它不使用jQuery中的任何其他内容。我想通过删除jQuery依赖项来减轻它。

如何在不使用jQuery的情况下实现我自己的$(document).ready功能?我知道,使用window.onload将不同,因为window.onlead在加载所有图像、帧等后启动。


当前回答

这个解决方案怎么样?

// other onload attached earlier
window.onload=function() {
   alert('test');
};

tmpPreviousFunction=window.onload ? window.onload : null;

// our onload function
window.onload=function() {
   alert('another message');

   // execute previous one
   if (tmpPreviousFunction) tmpPreviousFunction();
};

其他回答

jQuery的回答对我很有用。经过一点重构,它很好地满足了我的需求。我希望这对其他人有所帮助。

function onReady ( callback ){
    var addListener = document.addEventListener || document.attachEvent,
        removeListener =  document.removeEventListener || document.detachEvent
        eventName = document.addEventListener ? "DOMContentLoaded" : "onreadystatechange"

    addListener.call(document, eventName, function(){
        removeListener( eventName, arguments.callee, false )
        callback()
    }, false )
}

编辑@duskwuff以支持Internet Explorer 8。不同的是,使用匿名函数对regex和setTimeout的函数测试进行了新的调用。

此外,我将超时设置为99。

function ready(f){/in/.test(document.readyState)?setTimeout(function(){ready(f);},99):f();}

与jQuery相比,使用JavaScript等价物总是很好的。一个原因是依赖的库少了一个,而且它们比jQuery等同物快得多。

jQuery等价物的一个极好的参考是http://youmightnotneedjquery.com/.

就您的问题而言,我从上面的链接中获取了以下代码:)唯一需要注意的是,它仅适用于Internet Explorer 9及更高版本。

function ready(fn) {
    if (document.readyState != 'loading') {
        fn();
    }
    else {
        document.addEventListener('DOMContentLoaded', fn);
    }
}

现在你应该使用模块。将代码放入模块的默认函数中,并将该函数导入脚本元素。

客户端.js:

export default function ()
{
  alert ("test");
}

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>test</title>
  </head>
  <body>
    <script type="module">
      import main from './client.js';
      main ();
    </script>
  </body>
</html>

2022版本

2022年,您需要做的就是将defer属性放在脚本上,并将其加载到头部!

参考:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-推迟

<!doctype html>
<html>
<head>
  <script src="/script.js" defer></script>
</head>
<body>

 <p>In 2022, all you need to do is put the defer attribute on your script, and load it in the head!</p>

</body>
</html>