Commit c0e4df7d authored by Mike Jang's avatar Mike Jang

Merge branch 'docs-update-note-about-dom-content-loaded' into 'master'

Update performance docs to reflect removal of `DOMContentLoaded` and usage of `waitForCSSLoaded`

See merge request gitlab-org/gitlab!46733
parents af754207 5f7fb04c
...@@ -97,16 +97,26 @@ browser's developer console while on any page within GitLab. ...@@ -97,16 +97,26 @@ browser's developer console while on any page within GitLab.
modules outside of the entry point script. Just import, read the DOM, modules outside of the entry point script. Just import, read the DOM,
instantiate, and nothing else. instantiate, and nothing else.
- **Entry Points May Be Asynchronous:** - **`DOMContentLoaded` should not be used:**
_DO NOT ASSUME_ that the DOM has been fully loaded and available when an All of GitLab's JavaScript files are added with the `defer` attribute.
entry point script is run. If you require that some code be run after the According to the [Mozilla documentation](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer),
DOM has loaded, you should attach an event handler to the `DOMContentLoaded` this implies that "the script is meant to be executed after the document has
event with: been parsed, but before firing `DOMContentLoaded`". Since the document is already
parsed, `DOMContentLoaded` is not needed to bootstrap applications because all
the DOM nodes are already at our disposal.
- **JavaScript that relies on CSS for calculations should use [`waitForCSSLoaded()`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/assets/javascripts/helpers/startup_css_helper.js#L34):**
GitLab uses [Startup.css](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/38052)
to improve page performance. This can cause issues if JavaScript relies on CSS
for calculations. To fix this the JavaScript can be wrapped in the
[`waitForCSSLoaded()`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/app/assets/javascripts/helpers/startup_css_helper.js#L34)
helper function.
```javascript ```javascript
import initMyWidget from './my_widget'; import initMyWidget from './my_widget';
import { waitForCSSLoaded } from '~/helpers/startup_css_helper';
document.addEventListener('DOMContentLoaded', () => { waitForCSSLoaded(() => {
initMyWidget(); initMyWidget();
}); });
``` ```
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment