Is it the last `script` element the currently running script?

前端 未结 3 419
感动是毒
感动是毒 2020-12-02 00:19

Is it safe to assume that the last script element* in the document when the script runs** is the currently running script?

For example, I want to create

3条回答
  •  一生所求
    2020-12-02 01:00

    I don’t think it’s a safe assumption at all, as browsers execute javascript code quite differently depending on a number of things (like if you have other script elements in the head, if they are external etc.).

    You should just require people to use a dummy element with a custom id or class. That way you will also make it possible to do whatever you do multiple times a page without having to run the script multiple times.

    This is also what is done when using widgets, for example Google’s +1 button.

    An alternative would be to use document.write to write additional content while the script is executed. This will not replace the script tag however, but simply add something after it.

提交回复
热议问题