Monthly Archives: July 2013

How To Dynamically Swap External Style Sheets with JavaScript

“There are very few things that surprise me.” – Judi Dench

Myself, I would not go as far as Dench – at least not in the world of Web development.  However, I will say that it isn’t everyday that I stumble upon something truly new (well to me) and delightful.  Nonetheless, not too long ago I discovered that it is possible to change external CSS style sheets for a running web page via JavaScript – i.e. dynamically, at will, after the page has loaded.  I confess I felt sheepish that I had not known this was possible.  Perhaps you didn’t know it either.  Read on if you wish and you’ll find out how.

Why is this ability to dynamically swap external style sheets useful?  There are at least three reasons:

  • In cases where a large number of individual CSS/style changes need to be applied all at once, this style sheet swap method might be faster to execute and easier to maintain.
  • The second reason is perhaps a specialized case of the general case stated above – this is a great way to implement dynamic theme changes that can be invoked by the user at any time.
  • The third reason is that this technique can assist with responsive web site design – i.e. changing the layout and sizes of element in a page to accommodate radically different screen sizes.  A more standard approach to responsive design relies on CSS media queries, which allows CSS to alter itself to accommodate different screen sizes.  Unfortunately, the sad reality of today is that many of the older mobile platforms (i.e. device, plus OS, plus mobile browser) do not properly support CSS queries.  Even on newer platforms, media query support can be quirky.  So one alternative approach is to substitute the technique being described in this article to allow for “responsive” CSS changes.  Instead of using media queries, JavaScript code can check the browser document size upon initial display and every refresh and then dynamically adjust font sizes, and specific DOM element dimensions by swapping in style sheets that have been created for best viewing at certain trigger sizes.

Actually accomplishing this feat is easier than one might expect – at the heart of it, there are only three standard, cross-browser DOM functions that need be employed for this purpose – removeChild, createElement and appendChild.  The basic idea is to remove one link element from the header of a page and add a new link element to replace it.  This methodology requires that two (or more) CSS files must already exist – no new CSS file is being created using this technique.  There are ways to dynamically create individual style sheet rules but this article does not cover that topic.  In any event – in my opinion – dynamically swapping entire style sheets is more useful.

To demonstrate actual swapping of external style sheets at run time I have built at a working demo page.  I will show every line of code and annotate how it works in the succeeding paragraphs, but it may be desirable to run the demo first.  Here is a link to the demo at my main site,  Check it out first or wait until after the explanation.  I’ll provide another link at the end of the article.

The demo consists of seven small files:

  • changecss.html
  • changecss.js
  • base.css
  • mono.css
  • red.css
  • green.css
  • blue.css

Only two of these files contain code and only one file, changecss.js, contains the actual code that enables the swap.  The base.css file contains all the non-swappable CSS used by the HTML for the demo, mostly formatting information that is non-color oriented – e.g. setting the sizes of things.  The other four CSS files represent themes.  It is these files that we can swap to change the theme of the demo page on the fly.  We’ll look at changecss.js first, then we’ll see how the single function in changecss.html calls the methods therein.

I like the names of functions and variables to be self-explanatory.  This means that to some people my function names may be annoyingly long.  I realize that this is a bit of a “religious thing” and not everyone likes the verbose approach – please forgive me if it rubs you the wrong way.  In any event, I list the content of the changecss.js file below.  It contains only two functions.

To make the swap, we need to first remove the existing external style sheet link.  For this purpose, we call upon the removeExternalStyleSheetLink function.  When first loaded, the demo page is linked to the theme CSS file named mono.css.  However, the demo user is allowed to swap in any of the other theme CSS files.  In order for this to happen, the demo first calls upon the removeExternalStyleSheetLink function to remove the link to mono.css, i.e.: <link id=”mono” rel=”stylesheet” type=”text/css” href=”mono.css” media=”screen” />.  Notice the rather unusual fact that the link has an id attribute – this is perfectly legal HTML (it’s just not done very often).  This id value of “mono” is the value that must be passed in the cssLinkId argument to the function.  The function uses it to get a reference to the DOM object of the external style sheet link that must be removed, and then does the removal by telling the parent of this DOM object to “remove me”.

Once the link to the original CSS theme file is gone, a new link element must be inserted into the head of the document to complete the swap.  For this purpose, we call upon the second function, createExternalStyleSheetLink.  The job of this function is to create a DOM object that will represent a link to the CSS file that is to be “swapped in”.  Like the removal function, the create function takes an id as an argument, because it is important to give this new link tag an id.  Giving it an id attribute makes it easy to reference it in case it too will be swapped out at some future time. The second argument, href, will of course contain the name of the CSS file that will be linked to (i.e. swapped in).  The function uses the standard DOM manipulation JavaScript functions createElement and appendChild to perform the work of creating the link object in memory and then inserting it into the proper place in the DOM. The proper place is in the head of the document, as denoted by the invocation: document.getElementsByTagName(“head”)[0].

Now let’s take a quick look at changecss.html.  I’ll list the entire file but the the main point of interest is the solo function named changeStyleSheet. Most of the rest of what is there merely exists to provide objects whose colors can be changed by a theme switch (i.e. proof of concept).  Note that I don’t necessarily advocate defining functions in HTML pages, but in this case, the function is quick and dirty and relies upon embedded page knowledge.  I’m doing a couple of other naughty things here, for instance, using a non-namespaced global variable.  Please bear in mind that I am striving for brevity and clarity of presentation – not necessarily trying to use best practices.

Before we look at the changeStyleSheet function, note again the link tag containing the id of “mono”.  That is the default theme that may be swapped out by pressing either the “Apply Red Theme”, “Apply Green Theme” or “Apply Blue Theme” buttons.  It is worth noting that the act of swapping the CSS files causes the page to radically change it’s appearance, but this does not cause a page refresh.

Because the functions in changecss.js have already been covered, there is nothing mysterious about the changeStyleSheet function.  We already understand how the removeExternalStyleSheetLink and removeExternalStyleSheetLink functions work, and the changecss.js function does little more than simply call them in succession.  The remainder of what the function does revolves around remembering the name of the CSS file for the current theme and displaying that information to the user.

The only remaining files to discuss are the CSS files – here is base.css.  This file never gets swapped out – which is of course the normal scenario for CSS files.  It performs a useful function in the demo by providing CSS that never changes, but its existence in the demo proves something as well.  The technique presented here is perfectly adept at “cherry picking” links – base.css remains undisturbed now matter how many times one swaps themes in the demo.

What follows after this paragraph are the listings of the four CSS files that could be considered to be “themes”.  There is nothing special at all about the makeup or structure of these files – they are just standard CSS files.  It is the JavaScript in changecss.js and the browser’s CSS engine itself that provide all the magic.

And there you have it – simple, sweet and powerful.  Here is that repeat link to the demo I promised I would provide.  If you haven’t yet done so, take a moment to play with it.

Understanding Open Source Licensing

“Liberty is the right to do what I like; license, the right to do what you like.” – Bertrand Russell

Russell implies that license means abrogation of rights.  In the world of open source software this quote is true – and yet in an important way, false.  The very idea of open source software licensing is intended to establish and guarantee right to use without any real financial cost.   However, monetarily free does not mean free in every sense of the word – there are restrictions on open source licenses.  The details of these license restrictions varies depending upon which open source license is employed – some are more restrictive than others.  To complicate matters even more, It can be argued that some types of restrictions are on the whole, beneficial.  With literally hundreds of distinct licenses in circulation, and bearing in mind the legalese in which most of these are wrapped, it is a daunting task to understand when and how a particular license license can safely be used.

This article is an attempt to demystify the most common of the these open source licenses.  It will also define – in layman’s terms – some of the language and concepts used in describing and discussing open source licenses.  However, take note before continuing on – the phrase “layman’s terms” is quite apropos – I am not a lawyer nor am I an expert on open source software licensing.  The information presented in this article is a distillation of information obtained by studying several different internet sources.

To simplify the task of understanding open source licensing, one can make use of three ideas:

  1. There are some basic similarities common to all open source licenses.
  2. Even the differences between common open source licenses can be reduced by grouping them into basic categories.
  3. In practice, there is only a small subset of these licenses that see frequent use.

Of the hundreds of licenses alluded to above, less than one hundred need be given any real consideration.  Even so, by applying the above ideas it is possible to reduce the number of licenses that must be considered to only seven or so, and each of these seven can be categorized as belonging to only one of two basic types.  However, before going into details I will define a small number of terms pertaining to open source software licensing.  The majority of these terms are useful in the context of this article and may also be useful on occasions when examining various open source licenses in the wild.

The following definitions of terms are useful in understanding open source software licensing:

Open Source Software – Executable or component software that is freely (both in cost and accessibility) available for private and commercial use.  Proprietary use may or may not be restricted, depending upon the type of license.

Private Use -  Any and all localized uses of the software, including modification, that do not involve redistribution for profit.

Commercial Use – Redistribution of the software as a product – in whole, part, derived or combinatorial work – in exchange for financial compensation.  An important point to bear in mind with this definition is that there is no attempt to limit or alter the original terms of the license.

Proprietary Use – In terms of open source software, “proprietary use” is a misnomer – once it becomes proprietary, it is no longer open source.  However, the concept can come into play with some types of licensing combinations.  A reasonable definition is that this is like commercial use, except that ability to limit or eliminate the impact of the original open source license has been granted or purchased.

Open Source License – A glob of text (typically less than around one thousand words) that indemnifies the creator/distributor against legal action, describes the rights of any would be user, and also potentially details limits of usage and distribution of the pertinent software.

Copyright – A legal device that guarantees the creator of a work the right to control its usage by others.  Copyright law provides the “teeth” for open source licenses.

Fair Use – Fair use is a legal concept that provides a limit to the manner in which copyright law may be enforced.  It generally applies to actual usage or output produced from a work, instead of restricting in what manner the contents of the work itself my be used.

Copyleft -  A copyleft clause in a license allows the open source use of a work by any party, but also mandates that any party who creates a derivative work must not change or disallow the rights detailed in the original open source license.  You might think of this in coding terms as a sort of “inheritance” for licenses.  The term “copyleft” has no legal meaning and derives it’s backing from copyright law.

Attribution Requirement – Typically this means that the license under which an open source product is distributed must be copied word for word into the source and/or documentation of any derivative product, if said product will itself be distributed.  Indemnification clauses are often bundled with the Attribution text.

License Compatibility – This term comes into play when one is considering distributing a derivative work that based upon open source works using different kinds of licenses.  The terms of some licenses are mutually incompatible.  On the other hand, some licenses are by nature compatible with other open source licenses.

Multiple (often Dual) Licensing – A mechanism whereby a software creator allows users of the work to use it under more than one license.  This offers the user a choice – either one or the other licenses will apply.  This technique is typically used to work around license compatibility issues in popular open source licenses.

So, what are the open source license commonalities?

  • All are created and offered with the philosophy that it should be possible to distribute useful software ideas and implementations in ways that do not result in their monopolization.  Sometimes the intent is purely altruistic and sometimes the idea is to promote mass distribution with the idea of eventual direct or indirect gain.
  • All are based upon copyright law.
  • All are intended to provide the software creator/distributor with some degree of legal indemnity against harm.
  • All require some form of attribution.

What basic differences exist between the different sorts of open software licenses and how to group similar types of licenses together for easier understanding?  Open source software licenses can be divided into two basic groups:  Those that employ “copyleft” and those that do not.  The intent of copyleft is to give all users the same rights as given to immediate or “first level” users of the software.  This generally translates into requirements for authors of derivative works to make freely available their changes to the original work – in other words, the changes to the open source software must also be open source.  While this is a laudable goal, it is more restrictive than the very permissive rules of non-copyleft open open source licenses.  This tends to prevent the adoption of copyleft solutions by some companies.

The most common examples of copyleft license open source software are those in the GNU Public License family, typically referred to as GPL.  The GPL licenses represent the first form of open source licenses that were introduced and are probably the most popular form of open source license in use today.  It is worth noting that even the wording of the license itself is copyrighted.  In the GPL family there are several similar licenses, the most common ones in use today being:

  • GPLv2 – a long time staple of the open source industry
  • GPLv3 – A revised revision of GPLv2 that aims at preventing tivoization and introducing greater compatibility with other licensing schemes.
  • LGPL – This family of GPL variants is similar to the GPL family, but use what is known as a “weak copyleft” scheme.  The first “L” in LGPL stands for library – not “Light”.  What the LGPL offers that a GPL does not is the ability to create a program that “dynamically links” to LGPL licensed products yet is not required to itself utilize the LGPL license.  The term “dynamic linking” refers to code accessing other discreet units of compiled code without embedding them.
  • AGPLv3 – Otherwise known as the Affero General Public License, is a GPL-like license with one big difference.  It is intended to stop scenarios such as web sites or other central network resources using open source licensed code to provide a service but without abiding by the open source license used in the creation of the centralized product.

The most common representatives of non-copyleft open source software licenses are BSD, MIT/X11 and Apache 2.0.  These licenses are very permissive, requiring only attribution in a prescribed manner.  The permissiveness is similar to that provided by public domain, aside from the need for attribution and the additional protections provided by concurrent disclaimers in these open source licenses.  Open software used under this kind of license is the kind most likely to end up in proprietary products.

  • BSD -  This may be the oldest and simplest form of non-restrictive open source licenses.  This is actually a family within itself but all are pretty similar.  The texts of the most common among these are not copyrighted.
  • MIT/X11 – Not much different than the BSD license family, but the wording more explicitly states the rights of users of the software.  The wording of this license is not copyrighted. Note that MIT has released other licenses in the past, which may differ from X11.  Nevertheless, the MIT/X11 license is often colloquially referred to as the “MIT” license.
  • Apache 2.0 – Similar in philosophy to BSD and MIT/X11, but much more verbose with more explicit wording yet, particularly including extra provisos regarding patent rights.  The Apache License requires preservation of the copyright notice and disclaimer.

We have arrived at last upon the take-away paragraph.  Here is the summary of what one needs to remember about open source licensing.  Bear in mind that I am not making recommendations here – I am only sharing my personal observations.  Use any of these in any manner at your own risk.

  • If you just want to use some free code and don’t care about or don’t want to maintain its “open-sourceness”, look for a BSD, MIT/X11 or Apache 2.O license.
  • If you want to use open source code and make sure your changes continue to say open source, look for a GPL license variant, but be ready to supply your source changes.
  • You will encounter other licenses that are not mentioned here.  A good first step in understanding licenses is to classify them as either the “copyleft” or “non-copyleft”. However, it is very important to understand all of the restrictions and rights associated with the license of any open source software if you change it – or even simply use it – in a product that you intend to make available for others.
  • When you combine open source material from multiple sources, you must ensure that the licensing constraints are compatible.  In general, extra care must be taken when copyleft licenses are involved, though some copyleft licenses, for example LPGv3, may be compatible with other licenses.
  • When dual or multiple licenses are offered, choose the one which best suits your own distribution and compatibility needs.
  • In virtually every case, open source software requires attribution.  Typically this consists of the requirement to redistribute the “license text”, which includes disclaimers of liability.  Licenses will explicitly state all details of the attribution requirements – and by law they must be followed if you wish to distribute software that uses the licensed product.