Lazy loading of jQuery with Tierra Templates

January 25th, 2010 by Doug Martin

If you don’t use jQuery on all your site pages why incur the cost of loading it? With Tierra Templates lazy loading of jQuery is easily accomplished by using conditional blocks in your templates.

As a simple example lets build a two page site – one page uses jQuery and the other doesn’t. Both pages share a common structure so lets define a parent template for both of them named _page.html:

<html>
	<head>
		[@ start jQueryInclude if jQueryOnLoad @]
			<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
			<script type="text/javascript">
				$(function() {
					[@ echo jQueryOnLoad @]
				});
			</script>
		[@ end jQueryInclude @]
	</head>
	<body>
		[@ echo content @]
	</body>
</html>

the _page.html template loads the jQuery file only if the jQueryOnLoad block is defined. Let’s see how we can use that in the page that uses jQuery:

[@ extends "_page.html" @]
 
[@ start jQueryOnLoad @]
	$(".testClick").click(function() {
		alert("clicked!");
	});
[@ end jQueryOnLoad @]
 
[@ start content @]
	<a href="#" class="testClick">test</a>
[@ end content @]

this template expands out to:

<html>
	<head>
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
		<script type="text/javascript">
			$(function() {
				$(".testClick").click(function() {
					alert("clicked!");
				});
			});
		</script>
	</head>
	<body>
		<a href="#" class="testClick">test</a>
	</body>
</html>

for the second page lets not define a jQueryOnLoad block:

[@ extends "_page.html" @]
 
[@ start content @]
	<a href="#" class="testClick">test</a>
[@ end content @]

this final template expands out to:

<html>
	<head>
	</head>
	<body>
		<a href="#" class="testClick">test</a>
	</body>
</html>

It’s as simple as that!

Bookmark and Share

2 Responses to “Lazy loading of jQuery with Tierra Templates”

  1. Gregory says:

    Of course (in theory) once you’ve loaded it once the browser cache should take care of any other instance on your domain.

    Granted there are edge cases where that doesn’t happen – but for the vast majority of cases you are adding extra code complexity for no benefit.

  2. Doug says:

    Gregory: this was just meant to be a simple example highlighting Tierra Template’s conditional block feature. I picked jQuery for no other reason that it’s widely used (and I use it). Next time I create a more complex example showing why conditional blocks are nice to use.

Leave a Reply