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.
Nevermind, solved
@BennyZ28 what was the solution?
@shilman Actually I haven鈥檛 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?
Most helpful comment
The workaround is too complex, why not storybook provide a callback just called after the story is added to the dom tree?