Javascript, execute scripts code in order inserted into dom tree

前端 未结 5 1504
囚心锁ツ
囚心锁ツ 2021-01-06 05:47

NOT A DUPLICATE AS I HAVE YET TO FOUND A SATISFYING ANSWER ON OTHER THREADS:

  • Load and execute javascript code SYNCHRONOUSLY
  • Loading HTML and Script o
5条回答
  •  广开言路
    2021-01-06 06:13

    if I insert two script tags, first and second, any code in first must fire before the second, no matter who finishes loading first. I have tried with the async attribute and defer attribute

    No, async and defer won't help you here. Whenever you dynamically insert script elements into the DOM, they are loaded and executed asynchronically. You can't do anything against that.

    My understanding is that RequireJS seems to be doing just this

    No. Even with RequireJS the scripts are executed asynchronous and not in order. Only the module initialiser functions in those scripts are just define()d, not executed. Requirejs then does look when their dependencies are met and executes them later when the other modules are loaded.

    Of course you can reinvent the wheel, but you will have to go with a requirejs-like structure.

提交回复
热议问题