in Javascript

Dynamically include Javascript within HTML body

Adding Javascript is a piece of cake when you have total editing control over the page. Unfortunately, the task is a little bit more tricky when you only have access to a part of the page body. Here is my solution.

<script> tags are blocking, meaning that your page will stop rendering until the code in the <script> tag is not fully loaded and executed. This is why it’s perfectly safe to include a JS library in <script> then to use it in another <script> tag:

Now, let’s say you have to include a Javascript library such as jQuery but you don’t know if it’s already been included or not. The proper way to achieve this would be to check if the jQuery object already exists then include jQuery by inserting a script element in the page head.

This looks clean, but it doesn’t work since the script won’t wait the appended <script> to be loaded and executed to continue its execution.

The only way to achieve this is the dirty old school way :

And then, it works! However, the page rendering may look glitchy because </script> tags are still blocking the rest of the HTML until their code is fully loaded.