Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

resourcesReady does not mean a script has finished parsing #179

Closed
ctmm opened this issue May 28, 2020 · 2 comments · Fixed by #184
Closed

resourcesReady does not mean a script has finished parsing #179

ctmm opened this issue May 28, 2020 · 2 comments · Fixed by #184
Assignees
Milestone

Comments

@ctmm
Copy link
Collaborator

ctmm commented May 28, 2020

The resourcesReady event does not take into account the fact that scripts might not yet have finished loading/being parse.
This creates a racing condition on certain projects, especially ones that attach component contructor functions to jQuery.

Screenshot 2020-05-28 at 16 16 38

@ctmm ctmm added this to the 3.0 milestone May 28, 2020
@ctmm ctmm self-assigned this May 28, 2020
@ctmm
Copy link
Collaborator Author

ctmm commented May 28, 2020

Proposed solution is to fire a scriptReady event from scripts added by the resource-loader, in the handler for javascript assets:

const emitScriptParsed = (nodes: HTMLElement[]) => {
  const scriptParsedEvent: CustomEvent = new CustomEvent('scriptParsed', { bubbles: true });
  nodes.forEach((node: Node) => {
    node.dispatchEvent(scriptParsedEvent);
  });
}

const onJsLoaded = (options: HandleOptions): void => {
    const script: HTMLScriptElement = document.createElement('script');
    script.src = options.resource.path;
    script.async = true;
    script.onload = () => emitScriptParsed(options.resource.elements);
    document.body.append(script);
}

const jsHandler: Handler = {
    match: isJs,
    handle: onJsLoaded
}

@ctmm
Copy link
Collaborator Author

ctmm commented May 28, 2020

Developers on codebases which use the legacy "evaled" data-init could then hook on this event to safely initialise any plugins:

window.addEventListener('scriptParsed', (event) => {
  const { target } = event;
  const intializationFunction = eval(target.getAttribute('data-init'));
  intializationFunction($(target))   
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant