Storybook: @storybook/html 5.0.1 can't run scripts on story load, aka 'DOMContentLoaded' doesn't help anymore

Created on 15 Mar 2019  ·  6Comments  ·  Source: storybookjs/storybook

Hi folks! So, here's my situation: some of my components require javascript. I can successfully call the javascript file in preview-head.html but, initialising it is a problem.

Before v5.0.1 I used to have:

document.addEventListener("DOMContentLoaded", function(event) {
        /* The stuff I needed to initialise */
    }, false);

and it worked, but now it doesn't.

I've been looking all over your docs and Stackoverflow itself but I can't find a solution to this. It feels like it should be something Storybook should be keeping in consideration.

Any help would be appreciated.

core has workaround question / support

Most helpful comment

@BennyZ28 what was the solution?

The workaround is too complex, why not storybook provide a callback just called after the story is added to the dom tree?

All 6 comments

Nevermind, solved

@BennyZ28 what was the solution?

@shilman Actually I haven’t solved it, I throught I had after too many hours in front of the screen but I was wrong.

So, any help still appreciated!

Whenever the 'page' changes, the old div#root element inside the iframe is removed and a new one is added. You can use this feature and combine it with MutationObserver to run a function each time the page changes.

Inside your preview-head.html, you can add:

function runOnInit() {
  console.log('Init')
}
function runOnPageChange() {
  console.log('Page has changed!')
}
document.addEventListener('DOMContentLoaded', function() {
  runOnInit();
  const callback = function(mutationsList) {
    for (let i = 0, len = mutationsList.length; i < len; i++) {
      if (mutationsList[i].type == 'childList') {
        runOnPageChange();
        break;
      }
    }
  };

  const observer = new MutationObserver(callback);
  const config = { childList: true, subtree: false };
  observer.observe(document.getElementById('root'), config);
}, false);

To understand how MutationObserver works, please refer to the MDN documentation.

🙏

@BennyZ28 what was the solution?

The workaround is too complex, why not storybook provide a callback just called after the story is added to the dom tree?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ZigGreen picture ZigGreen  ·  3Comments

Jonovono picture Jonovono  ·  3Comments

zvictor picture zvictor  ·  3Comments

wahengchang picture wahengchang  ·  3Comments

rpersaud picture rpersaud  ·  3Comments