Dynamically require/include a Javascript file into a page and be notified when its loaded


This is a simple little JavaScript snippet I wrote the other day that basically includes an external javascript file in an HTML page head section.

Its pretty straight forward,

  • it first gets a reference to the head tag.
  • Creates a script element using document.createElement
  • Sets the source/url of the file
  • sets the type of the script element to the correct mime type of “text/javascript”
  • Then sets the onload property of the script element to a callback function you supply. In i.e. it will check the onreadystatechange and execute the callback function you provide.
  • And finally it appends the script element to the head of the page

		/**
		 *Load an externl JS file and append it to the head
		 */
		function require(file,callback){
			var head=document.getElementsByTagName("head")[0];
			var script=document.createElement('script');
			script.src=file;
			script.type='text/javascript';
			//real browsers
			script.onload=callback;
			//Internet explorer
			script.onreadystatechange = function() {
				if (_this.readyState == 'complete') {
					callback();
				}
			}
			head.appendChild(script);
		}

Probably a million and one ways to do this but it works decently in I.E 7+,Firefox,Chrome,Safari and Opera

Quick tips for squeezing performance out of Google’s Javascript charts with live (continuous) data/streams


I, until a few days ago always used JQuery for literally everything that needed Javascript. I’ve recently needed to use Google charts to show a live graphical representation of data. It needed to be a widget that didn’t rely on any framework so I had to brush up on my Javascript and forget all the easy stuff JQuery usually gives me! The chart would be updated EVERY SECOND, yeah pretty often! In every second there could be any amount of new points to be plotted. In addition, I’m only interested in points that have occurred within a fixed time period, the results of all this will be an “animated” graph that shifts left when data is updated. Read more of this post

Follow

Get every new post delivered to your Inbox.

Join 1,384 other followers

%d bloggers like this: