tc39 / proposal-dynamic-import

import() proposal for JavaScript
https://tc39.github.io/proposal-dynamic-import/
MIT License
1.86k stars 47 forks source link

Make importing fail if URL has changed (for SPA, PJAX, and History API) #50

Closed falsandtru closed 6 years ago

falsandtru commented 7 years ago

After url and dom are changed by SPA or PJAX, requested scripts must NOT be evaluated. So importing must have failed if url has changed.

If it is not a module script, we can cancel the evaluation of that. But if it is a module script, we cannot cancel the evaluation of that.

Here is my code having this problem.

  const url = new URL(standardizeUrl(location.href));
  if (script.type.toLowerCase() === 'module') {
    return wait.then(() => import(script.src))
      .then(
        () => (
          void script.dispatchEvent(new Event('load')),
          Right(script)),
        reason => (
          void script.dispatchEvent(new Event('error')),
          Left(new FatalError(reason instanceof Error ? reason.message : reason + ''))));
  }
  else {
    return script.hasAttribute('defer')
      ? wait.then(evaluate)
      : evaluate();
  }

  function evaluate() {
    try {
      if (new URL(standardizeUrl(location.href)).path !== url.path) throw new FatalError('Expired.');
      if (skip.has(standardizeUrl(location.href))) throw new FatalError('Expired.');
      void (0, eval)(code);
      script.hasAttribute('src') && void script.dispatchEvent(new Event('load'));
      return Right(script);
    }
    catch (reason) {
      script.hasAttribute('src') && void script.dispatchEvent(new Event('error'));
      return Left(new FatalError(reason instanceof Error ? reason.message : reason + ''));
    }
  }

https://github.com/falsandtru/pjax-api/blob/ae05475a829974d634b46ac346939a599c90545b/src/layer/domain/router/module/update/script.ts#L123-L152

falsandtru commented 7 years ago

Moved to https://github.com/whatwg/loader/issues/158

falsandtru commented 6 years ago

Since https://github.com/whatwg/loader/issues/158

domenic commented 6 years ago

This seems like a question for StackOverflow, not the spec. It's a lot of code that I don't have the bandwidth to debug for you, but hopefully volunteers there can help.

matthewp commented 6 years ago

I believe this is a feature request, aborting an import.

matthewp commented 6 years ago

If I'm correct in that interpretation you might be interested in https://github.com/tc39/proposal-dynamic-import/issues/42 @falsandtru

falsandtru commented 6 years ago

I believe this is a feature request, aborting an import.

I think so, but @caridy redirected to here. This issue demonstrate a need of cancelable dynamic import. This issue must be resolved by design of es or whatwg. It is impossible to resolve this case at downstream.