iPeng6 / docsify-sidebar-collapse

a docsify plugin, support sidebar catalog expand and collapse
MIT License
176 stars 37 forks source link

Trees don’t collapse when using deferred scripts #15

Closed edukisto closed 3 years ago

edukisto commented 3 years ago

I import scripts into <head> and use the defer attribute. As a result, the /pages/ tree doesn’t collapse because there is no .sidebar-nav at the DOMContentLoaded moment.

Consider the following directory structure:

docs
├── _sidebar.md
├── index.html
├── init.js
├── pages
│   ├── page-1.md
│   ├── page-2.md
│   └── README.md
└── README.md

_sidebar.md:

- [Does not toggle!](/pages/)
    - [Page 1](/pages/page-1)
    - [Page 2](/pages/page-2)

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
  <title>Document</title>
  <link
    rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/docsify@4.11.6/lib/themes/vue.css"
    integrity="sha256-GVgqM6L5FlZZv53JoPI27I3UmnRdOX6BLH987DPeNro="
    crossorigin="anonymous"
    >
  <script
    defer
    src="init.js"
    ></script>
  <script
    defer
    src="https://cdn.jsdelivr.net/npm/docsify@4.11.6/lib/docsify.min.js"
    integrity="sha256-zTTKqWPEpPgRygl1gorAx8ux6HjMcv+zhnqoPp6XWOU="
    crossorigin="anonymous"
    ></script>
  <script
    defer
    src="https://cdn.jsdelivr.net/npm/docsify-sidebar-collapse@1.3.3/dist/docsify-sidebar-collapse.js"
    integrity="sha256-TfNIbrnq1RnOZHFkUZCex03B9ZoDbeskY+UQH5lQ0Kk="
    crossorigin="anonymous"
    ></script>
</head>
<body>
  <div id="app"></div>
</body>
</html>

init.js:

(function (window) {
  'use strict';

  window.$docsify = {
    alias: {
      '/.*/_sidebar.md': '/_sidebar.md'
    },
    loadSidebar: true,
    subMaxLevel: 3
  };
}(window));

I think it’s better to replace the addEventListener() call with a hook.