Include Javascript conditionally in page

Goal

Include a Javascript library only if it has not been included yet

Description

Imagine that you are in a JSF project with a few GUI libraries being included in your base template. Imagine also that you have some components that include a few Javascript libraries conditionally, depending on their usage. Now, imagine that you always want one of those conditionally included Javascript libraries in your template and that you do not want that library included more than once. This recipe shows a way to avoid that duplicate inclusion.

How to

The trick in this recipe is to check for the existence of a specific thing that library defines. For instance, checking if the jquery object already exists in the context of the page and do something only when it does not exist. So, in the next code snippet, which could be included in a facelets template of a JSF application, one could specify that need based on the existence of the jQuery object:


  // using jquery that is being used by JSF
  window.jQuery || document.write("\x3C/script>")
  

Prety easy, hum? We check if the object jQuery exists and, if it does not, (if the first check of the or expression succeeds, it simply returns!) we include a small block of HTML to include the jquery javascript file, included somewhere in your project (the $javascript_folder)

Explanations

To summarize things up in this recipe, we include the HTML script tag in the template header through the Javascript expression document.write() if and only if the object jQuery is not defined yet

This recipe is not a wonderful one but has proved to be useful before for me. Maybe it may be useful for someone else too. Hope you enjoy it!

Advertisements

2 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s