为什么我的外部资源在 JSFiddle 中不起作用?

Why does my external resource not work in JSFiddle?

我创建了一个简单的 package for collapsible elements with an option to close the element when clicked outside of it with an attribute data-close-on-click-outside. Locally it works, and also if I were to copy the JS into JSFiddle it works, but when I include the JS from a CDN, the event listener does not seem to be triggered. An example can be seen in this JSFiddle为什么我的代码在作为来自 CDN 的资源包含在 JSFiddle 中时不起作用?

n.b.: 我不认为我的代码有什么问题,因为除了 JSFiddle(无论是否缩小),它在任何地方都有效,但为了完整起见,这里是我的代码:

HTML

<button data-collapsible-target="collapsible-close">Toggle me</button>
<div class="collapsible-close" data-close-on-click-outside>
    This *should* close when clicked outside...
</div>

JS

document.addEventListener('click', (event) => {

  const element = event.target;
  const targetSelector = element.getAttribute('data-collapsible-target');

  if (targetSelector !== null) {
    toggleCollapse(targetSelector);
  }
}, false);

const toggleCollapse = targetSelector => {
  const targets = document.querySelectorAll('.' + targetSelector);
  targets.forEach(target => {
    if (!target.classList.contains('collapsible-show')) {
      target.style.maxHeight = target.scrollHeight + 'px';
    } else {
      target.style.maxHeight = 0 + 'px';
    }
    target.classList.toggle('collapsible-show');
  });
}

const closeOnClickOutsideElements = document.querySelectorAll('[data-close-on-click-outside]');
closeOnClickOutsideElements.forEach(element => hideOnClickOutside(element))

function hideOnClickOutside(element) {
  const outsideClickListener = event => {
    // Third checks if the element clicked isn't the toggler, which would result in a double click event that conflict each other.
    if (!element.contains(event.target) && isVisible(element) && !element.classList.contains(event.target.getAttribute('data-collapsible-target'))) {
      element.classList.remove('collapsible-show')
      element.style.maxHeight = 0;
    }
  }
  document.addEventListener('click', outsideClickListener)
  const isVisible = elem => !!elem && !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length) // source (2018-03-11): https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js
}

编辑: 弄明白了,请参阅下面的答案。

JSFiddle 加载文件 <head> 中的资源。如果将此资源添加到 <body> 的末尾,结束标记 </body> 之前,则该资源有效。如果我希望能够在包含在文档的 <head> 中时使用它,我可以通过将其包装在 document.addEventListener("DOMContentLoaded", function() {}); 中来更改脚本。