Search code examples
javascriptdeferred-execution

Execution order of dynamically added script tags marked with defer attribute?


I have some applications which dynamically create widgets. Some widgets need some libraries to be included (eg Codemirror, Tinymce, jQuery, ..). These scripts are dynamically added in document when the widget is first created, else they are not included at all (it would be a waste of resources to pre-include all possible widget scripts without them being used in every request).

The widgets can be created either server-side or client-side. In client-side the scripts are added dynamically on page else added as script tags by server in the resulting html output.

If on client, I have noticed that execution order is not respected. For example some Codemirror addons load first (as more light-weight) yet they fail because the main lib s not yet loaded (even though it comes before them as script tag).

I tried using defer attribute which according to MDN respects the execution order as it appears, even though scripts are loaded async. Yet I noticed it fails (note I use only defer attribute not async). Tested on Firefox and Chrome so far.

Is this true also for dynamically added script tags?

If not, what can be an alternative in order to respect execution order (without using onload callbacks)?

Thank you!


Solution

  • I resolved the issue by using callbacks to wait until a script has loaded before attaching a new script on the DOM (which depends on previous script).

    However I would expect this procedure to be handled by browser (eg using defer attribute).

    If someone has a solution in which the browser handles all this interlinking for dynamically added script tags, please feel free to post an answer.