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:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
	// At this point, jQuery has been loaded and is available
	$(document).ready(function() {			
		$('body').css({background: '#00B000'});
		alert('done!');
	});
</script>

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.

<script type="text/javascript">
	// Load jQuery if not already included
	if (typeof jQuery == 'undefined')
	{
		var script = document.createElement("script");
		script.type = "text/javascript";
		script.src = "http://code.jquery.com/jquery-1.11.1.min.js";
		document.head.appendChild(script);
	}
	
	// At this point, the jQuery script tag is added in page <head> but not yet fully loaded
	$(document).ready(function() {			
		$('body').css({background: '#00B000'});
		alert('done!');
	});
</script>

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 :

<script type="text/javascript">
	<!--
	// This code will add a new <script> element just after the current one
	// It is important to wrap this code in an HTML comment tag to avoid the closing script tag in the lines below to be parsed by the browser
	if (typeof jQuery == 'undefined')
		document.write('<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>');
	-->
</script>
<script type="text/javascript">		
	// At this point, jQuery has been loaded and is available
	$(document).ready(function() {			
		$('body').css({background: '#00B000'});
		alert('done!');
	});
</script>

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.