Tag Archives: Javascript

Discovering Web Workers

So I wanted to learn about Web Workers, since they are (as far as I have come to understand) the only real way of running javascript in a separate thread. The following post is my explanation of the concept as I have percieved it at the time of learning.

Note: I wrote this post in the process of learning, meaning I’m not an expert. Don’t take my word as the truth. They’re just my interpretation of what others have said, and my own tests.

Web Workers

Web Workers allows running scripts “in the background”, in a separate thread from that of the user interface, allowing tasks to be performed without disturbing the user experience. Since javascript is a single threaded language, only able to simulate multithreading by using for example yield() or setInterval(), workers might be the only option for running javascript in separate threads. At least as far as I know.

Some things to know about web workers

  • Workers have a high start-up performance cost
  • Each worker instance consume a high amount of memory
  • Workers are not intened to be used in large numbers at the same time

A worker should not be something you call frequently to perform small tasks, since the cost of calling the worker will exceed the benefit of running it in a separate thread.

So when do you use Web Workers then? Well, if you want to run something that has a high performance cost, without interfering with the user experience, web workers can be a viable option. Uses can include for example perform heavy calculations, or having a “listener” for notifications running in the background.

So how do you do it?

Simple example

First of all, I have a simple html page, with a span to post my results, and buttons to start and stop my worker.

<html lang="en">

 <input type="button" onclick="startWorking();" value="Start working!">
 <input type="button" onclick="stopWorking();" value="Stop working!">


 Results: <span id="resultSpan">...</span>

 <!-- load scripts at the bottom of your page -->
 <script src="javascript/foreman.js"></script>

Next, I have a javascript file being loaded to the page. This is not my worker, but the script responsible for calling the worker. I call it foreman.js.

The first thing I want to do is to get my resultSpan element to present the results of the workers. I also create a variable for storing my worker object.

var result = document.getElementById("resultSpan");
var worker;

Next I create a function for stopping the worker.

function stopWorking() {
 worker.terminate(); // Tell the worker to stop working.
 worker = undefined; // Fire the worker.

Not all browsers support workers, so a function to check for worker support might be a good idea.

function browserSupportsWebWorkers() {
 if(typeof(Worker) !== "undefined") {
 // Yes! Web worker support!
 return true;
 } else {
 // Sorry! No Web Worker support..
 return false;

And now to the important parts. We want to be able to call our worker, and create a function for doing just that.

function startWorking() {
// Code goes here.

The first thing I do is checking if the browser supports workers. If it doesn’t, I can handle it in different ways. This is good if you don’t want your functionality to break due to compatibility issues.

 if (!browserSupportsWebWorkers()) {
 // What to do if browser doesn't support workers.

Then I instantiate a new worker object, referencing the worker javascript file. And yes, the worker code needs to be located in a separate file.

 worker = new Worker("javascript/worker.js"); // Create a new worker object.

// Code goes here.

Now when we have the worker object, we need to define what will happen when we get a response from it.  Communication between the foreman and worker will be passed through messages, and we need to declare what to do with those messages. The code below shows 2 ways of doing the same thing.

 worker.onmessage = function(event) { // Tell the foreman what to do when the worker response comes.
   result.innerHTML = event.data;

 // This is another way of doing the same thing.
 worker.addEventListener("message", function (event) {
   results.innerHTML = event.data;
 }, false);

In the code above, we declare that when we recieve a message from the worker, we will get that message and show it in our resultSpan by setting its innerHTML.

We may also want to handle what happens if an error occurs. In addition to the .onmessage event, we can declare the .onerror event for just this reason.

worker.onerror = function(event) { // Tell the foreman what to do when the worker fails.
   result.innerHTML = "Error: " + event.message;

The last thing is to call the worker. This is done by calling the postMessage function of the worker object.

worker.postMessage(); // Tell the worker to start working.

What will happen now is that the worker javascript will be loaded and executed. The results will depend on what we put in the worker.js file. All we have done in foreman.js is to say that we will present the results of the worker. So let’s take a look at the actual worker: worker.js.

var i = 0;

function timedCount() {
 console.log("Worker says: Counting to " + i);
 i = i + 1;


In this simple example, all I want to do is to illustrate a continuous process being run in the background. The worker runs a recursive function every 500 milliseconds and sends the response back to the foreman. The message is being passed by calling the postMessage function. The object put as a parameter in postMessage will be available in event.data in the foreman script. In this case it’s an integer, but it could just as well be a string or JSON object.

Calling specific worker functions

You cannot call a specific function within a worker directly. When the worker is called, it simply runs the file. However, you can implement your own handling by passing function names as parameters.

In my next example, I have another worker file, skilledWorker.js. It contains three functions. I choose to store these in an object called actions, and you will see why later. This is not required however, and there are many ways of implementing support for calling certain functions.

var actions = {};
actions.count = function (parameters) {
  // Unpack parameters.
  var number = parameters;

  setTimeout(function () { // Call setTimeout to run function each 1000 ms.
    postMessage(number); // Message the foreman of the current number.
    number++; // Increment number.
    actions.count(number); // Recursively call the same function to increment number with each call.

actions.calculate = function (parameters) {
  // Unpack parameters.
  var a = parameters.a;
  var b = parameters.b;

  var results = a + b;

actions.read = function (parameters) {
  // Unpack parameters.
  var results = parameters.text;

Next, I need to declare what will happen when my worker receives a message.

self.onmessage = function (event) {

This says that I should call the function handleMessage and pass my event whenever a message is received. All that’s left is implementing the handleMessage function.

function handleMessage(event) {
    var command = event.data.command;
    var parameters = event.data.parameters;
    var action = actions[command];
    if (action) {
    else {
        postMessage("Unknown command");

What happens here is that we retrieve the event.data, and get two properties from it, command and parameters. These has to be passed when calling the worker, and I will show how in a bit.

The next piece of code I got a little help from my friend and colleague Anatoly Mironov who has one of the best SharePoint blogs out there.

Since we store our functions in the object called actions, calling “actions[command]” will return the function matching the command string. If no functions matches, the value will simply be undefined. The simple if-statement allows you to check and handle what happens when trying to call a function that doesn’t exist.

The last thing we need to do is to call the worker passing the correct command and parameters.

Passing parameters

Calling a worker with parameters is still done with postMessage(). You can pass either a string or a JSON object. This example will demonstrate how to pass a JSON object. Passed parameters will be available in the worker in event.data. As you saw above, our workers handleMessage function needed the data to contain .command and .parameters. So when calling postMessage() we simply input a JSON object containing these two values.

worker.postMessage( { 'command': 'count', 'parameters': 1 } ); // Tell the worker to start counting.

worker.postMessage( { 'command': 'calculate', 'parameters': {'a': 5, 'b': 10 } } ); // Tell the worker to calculate.

worker.postMessage( { 'command': 'read', 'parameters': {'text': 'This is text the worker is supposed to read.'} } ); // Tell the worker to read the text.

In the code above, each  line will call the worker, but running different functions, which in turn use different parameters.

In conclusion

Web workers are not very difficult to work with once you understand how they work, and while their use might be limited due to the heavy initial performance cost, being able to running a background thread for large tasks can be quite powerful.

If you want to check the full code I have a GitHub repository for it here: https://github.com/Johesmil/webworkers.

If you want to learn more about Web Workers from people who actually know what they’re talking about, check out the links below. =)


Web Workers


Embedding a PDF file dynamically on a web page

So embedding a PDF to a web page is pretty easy. All you need to do is to add an object or embed element to your HTML.

Actually, you could use only object or embed, depending on browser support. But using both is a safeguard. If object fails to load it’s data, it will render it’s child elements instead, in this case the embed element.

< object data='myPDF.pdf' type='application/pdf'>
 < embed src='myPDF.pdf' type='application/pdf'></embed>

There are spaces between the < and object/embed elements since WordPress doesn’t allow these elements. Remove it if copying this code.

But what if you don’t know what PDF file you want to display, and you want to load it dynamically? This is what I was trying to do, and of course I ran into problems displaying the PDF in Internet Explorer. This is how you should be able to set which file will be loaded using javascript. First, we add the elements to our HTML. To make it easier to get the elements in our javascript, give them a unique id.

< object id='myPdfObject' type='application/pdf'>
 < embed id='myPdfEmbed' type='application/pdf'></embed>

Then, in javascript, we SHOULD be able to change witch PDF should be shown like this.

// Get the elements.
var pdfViewerObject = document.getElementById("myPdfObject");
var pdfViewerEmbed = document.getElementById("myPdfEmbed");

// Set the elements to reference our PDF file.
pdfViewerObject.setAttribute("data", pdfUrl);
pdfViewerEmbed.setAttribute("src", pdfUrl);

It works perfectly in Chrome, but in IE (tried versions 10 and 11 as well as emulated 8 and 9), you will only see a grey frame with nothing in it. When debugging the javascript the attribute is actually updated, and everything seems to be fine, except you can’t see the PDF. Very frustrating. After a bit of googling i found a solution here (it’s not the marked answer). Instead of using <element>.setAttribute(), which should work, you need to modify the outerHTML attribute of the element.

pdfViewerObject.outerHTML = pdfViewerObject.outerHTML.replace(/data="(.+?)"/, 'data="' + pdfUrl + '"');
pdfViewerEmbed.outerHTML = pdfViewerEmbed.outerHTML.replace(/src="(.+?)"/, 'src="' + pdfUrl + '"');

However, this will only work if you already have the attribute present. So either you need to have a default url in your HTML, or you need to set the attribute first, which both is kind of annoying. Putting it all together it might look something like this.

var pdfUrl = "http://mySite/myPDF.pdf";

var pdfViewerObject = document.getElementById("myPdfObject");
pdfViewerObject.setAttribute("data", pdfUrl);
pdfViewerObject.outerHTML = pdfViewerObject.outerHTML.replace(/data="(.+?)"/, 'data="' + pdfUrl + '"');

var pdfViewerEmbed = document.getElementById("myPdfEmbed");
pdfViewerEmbed.setAttribute("src", pdfUrl);
pdfViewerEmbed.outerHTML = pdfViewerEmbed.outerHTML.replace(/src="(.+?)"/, 'src="' + pdfUrl + '"');

And there you go. Dynamically loading an embedded PDF to a web page, working in IE 8-11 and Chrome, and hopefully other browsers as well.

My main sources/further reading:

Automatic minifying of CSS (and LESS) and javascript using Web Essentials 2013 in Visual Studio 2013

We just recently started upgrading to Visual Studio 2013 in the project I’m currently working on, and with VS 2013 comes Web Essentials 2013, an extension that’s truly essential for web development.

Now, I like to use the LESS framework when writing CSS, and have been using Web Essentials 2012 for some time. One of the nice things about LESS and Web Essentials 2012 was that it automatically generates a minified version of the CSS file for you, and that’s pretty sweet.

Now, one of the first thing we noticed in VS 2013, was that modifying and saving our LESS files no longer generated a minified version of that file.

No mini

At first we thought it might be a bug, but when exploring the toolbar menu for Web Essentials (new to 2013), we found an interresting button:

Toolbar menu

Pressing this created a settings file and added it to the solution. In this file we found a number of awesome stuff. For example, you could turn the automatic generation of CSS files on and off. And even better, there was even an option to do the same for our javascript files!


Now we were getting our minified CSS files just like before, and also having the same behavior for our javascripts!

Yes mini

Before, we used another VS plugin for generating our minified javascripts, but now we no longer need to. Everything is taken care of using Web Essentials 2013, and modifying the settings file.

Perhaps the best thing about the created settings file is that it is automatically added as a solution file, and picked up by the source controller. So once configurated, we can just check in the file and let everyone in the team get the correct behaviour automatically.

Now, I may be ignorant of what was possible in 2012. Perhaps this settings file was available, and perhaps they had support for minifying javascripts. But since Web Essentials are now more visible than before (having its own toolbar menu), finding these features was easier, and took only a few minutes to figure out, without googling for help or reading any Product Updates info. And to me that’s pretty sweet! =)

Making use of localized variables in javascript.

Here is a simple way of using values stored in global resource files to be used in your markup and javascript code. Simply add the following to your markup (aspx page, user control or whatever).

<script type="text/javascript">
    var myVariable = '<%= GetGlobalResourceObject("MyResourceFileName", "MyResourceKey").ToString()%>';

Once this is done, you can make use of the variable in your javascripts.

Note: These variables cannot be added in separate javascript files, but have to be added to the page directly. However, once added, they can be reached from code in the javascript file if it is imported.

EDIT: The GetGlobalResourceObject method is a standard method in the HttpContext class (link here).

Reload page from code behind

I can’t believe there isn’t an easier way to do this. Anywas, I wrote this method to force a page reload since I didn’t want my page to reload by postback. It’s using javascript, but you don’t have to write anything else except this method here. No changes needed, just copy-paste.

protected void ReloadPage()
 string script =
  @"<script language='JavaScript'>
 ScriptManager.RegisterClientScriptBlock(this, this.GetType(), string.Empty, script, false);

EDIT: using  ‘window.location.reload()’ can cause a problem in IE where you initiate an endless reload loop with an error message poping up endlessly. The problem was solved for me by replacing it with:



The script string is just a regular javascript used for reloading pages. The ScriptManager.RegisterClientScriptBlock method is used to run the script. It has five parameters:

  1. The control which is to register the script. Use ‘this’.
  2. The type of the client script block, or rather the type of the control you put in as the first parameter. Use ‘this.GetType()’.
  3. A key string. I don’t even know what it’s for. Just use an empty string or whatever.
  4. The script string itself.
  5. A boolean value determining if the tags ‘<script> </script>’ should be put around your script string. In this case you can choose false.

Neat confirmation using jQuery

I was looking for ways to do some simple yes/no client-side confirmation and found a nice plugin using jQuery. I am a total noob when it comes to jQuery (in fact this is the first thing I have ever done) so with a little help from a collegue I got it working. Its pretty simple. All you need to do is:

  1. Download the plugin. It is a javascript file.
  2. Import the javascript file to your page.
  3. Write the function which is to be run.

I’m sure some of the code in my example is very specific to my environment. But I know way to little to make a well-explained generic post about it.

My button which will execute the script looks like this:

<asp:Button ID="ButtonDeny" runat="server" Text="Godkänn" OnClick="ButtonDeny_Click" />

Import the plugin to your page like this:

<script type="text/javascript" src="/_layouts/WebParts/jquery.confirm-1.3.js"></script>

I put the jQuery function inside a pageLoad for it to get the correct client-side ID of my button:
NOTE: This pageLoad function is put inside the script tags of my ascx or aspx page.

function pageLoad(sender, args) {

            msg: 'Are you sure you want to do this??',
            separator: ' / '

This will prevent the postback and the server-side method being called when I click the button, unless I choose ‘Yes’ when asked. Very neat indeed. I found this plugin here.

CheckBox header to select/deselect all checkBoxes in SPGridView using javascript

So I wanted to have a checkBox header in my SharePoint:SPGridView that checked all the checkboxes in that column of my gridview. I also wanted to do this client-side since it is (at least for me) totally worthless to do a postback to the server just to check the boxes. So I used javascript. I found a couple of solutions out there, and combined two of them to match my needs. Links are at the bottom of this post.

Below is the code I run to perform this task:

The SPGridView control:

<SharePoint:SPGridView ID="mySPGridView" runat="server" AutoGenerateColumns="false" >
    <asp:CheckBox ID="selectionCheckBox" runat="server" />
    <asp:CheckBox ID="selectionCheckBoxHeader" runat="server" OnClick="checkAllCheckBoxes(this)" />
   <HeaderStyle HorizontalAlign="Left" />

Not that I call the function by using OnClick because I want it to run on client-side. This does not appear as an option in intellisense when writing the code, instead you get the suggestion to use OnCheckedChanged. Do not use this since that will try to call a method on the server side. Write OnClick instead. It will work (at least it did for me).

The javascript function:

function checkAllCheckBoxes(invoker) {	
	var gridView = document.getElementById('');
	for (var i = 1; i < gridView.rows.length; i++) {
		var rowElement = gridView.rows[i].cells[0];
		for (var j = 0; j < rowElement.childNodes.length; j++) {
			if (rowElement.childNodes[j].type == "checkbox") {
				rowElement.childNodes[j].checked = invoker.checked;

Note: I was a few ppl mention how much easier it was doing this in  jQuery. I really need to start learning jQuery soon.

Source links:

1: Check/uncheck CheckBox in a GridView using Javascript

2: Check/Uncheck checkboxes in GridView using JavaScript

asp:CustomValidator for asp:CheckBoxList with multiple javascript validations

This one I struggled with for a long time. Mostly because I am still inexperienced when it comes to javascript. I wanted to create a CustomValidator which checked if at least one box was checked, if the boxes checked where consecutive, and lastly that the correct number of boxes where checked depending on the selection in another control.

You basically need three things to make this work:

  1. A CheckBoxList (Or any other control you want to validate)
  2. A Custom Validator (I use the already existing asp:CustomValidator, but you can make your own if you want)
  3. A javascript function to handle the logic

I ran into a number of problems, which were mostly due to my own inexperience rather than the problem being too complicated. One issue you run into when validating a CheckBoxList is that the validator won’t work if you use the attribute “ControlToValidate” on your asp:CustomValidator as you do with other controls. Instead you have to retrieve the control inside the javascript function which will be used to validate. The way I found to do this was by using document.getElementById(CheckBoxListID) inside your function.

var timeslotCheckBoxList = document.getElementById('<%=Timeslots.ClientID%>');

The problem with using “<‘%=Timeslots.ClientID%>’ is that you cannot use external javascript files, or at least so I read in some forums. This mean you have to put your functions directly into the page where the controls exist. This only applies when validating CheckBoxList (and other controls not compatible with CustomValidator) though, since you can normally use the  “ControlToValidate” attribute in the validator to retrieve the control into the function:

<asp:CustomValidator ID="myValidator" runat="server" ControlToValidate="myTextBox" ErrorMessage="Run for your lives!" ClientValidationFunction="validateTextBoxTimeslots" ValidationGroup="Test">

In this case you would be able to retrieve the control through the sender parameter in the function, and the value of the control through the args parameter (parameters are shown in the full example code at the end of the post)

I have chosen to keep “ValidationGroup” in the example aswell since it is a great way to make sure you trigger the right validators at the right time. Just give the button or other control you want to trigger the validation the same attribute and value and no other button or control will.

Below is the fully working code example:

<asp:CheckBoxList ID="Timeslots" runat="server" >
<asp:CustomValidator ID="myValidator" runat="server" ErrorMessage="Run for your lives!" ClientValidationFunction="validateCheckBoxListTimeslots" ValidationGroup="Test">
<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="Test" /> 

Javascript functions:

The first function creates an array with the number of selected timeslots and checks if at least one slot has been selected. It is also here that the other two checks are made, and the error messages are set.

function validateCheckBoxListTimeslots(sender, args) {
            var timeslotCheckBoxList = document.getElementById('<%=Timeslots.ClientID%>');
            var timeslots = timeslotCheckBoxList.getElementsByTagName("input");
	    var checkedTimeslots = new Array();
            var arrayIndex = 0;
            for (var i = 0; i < timeslots.length; i++) {
                if (timeslots.item(i).checked) {
                    checkedTimeslots[arrayIndex] = timeslots.item(i);
            args.IsValid = true;
            if (checkedTimeslots.length == 0) {
                args.IsValid = false;
                sender.innerText = "Select at least one timeslot.";
            if (checkTimeslotsIfConsecutive(checkedTimeslots) == false) {
                args.IsValid = false;
                sender.innerText = "Timeslots must be consecutive.";
            if (checkTimeslotsIfCorrectNumberOfSlots(checkedTimeslots) == false) {
                args.IsValid = false;
                sender.innerText = "Incorrect number of timeslots.";

The second function checks if the selected timeslots are consecutive. The logic is simple. Each checkBox has a text value which represents a time interval, for example (10:00-10:15). All I have done is to split the values on the “-” sign, and compare the end time of the first timeslot with the start time of the second timeslot.

function checkTimeslotsIfConsecutive(checkedTimeslots) {
            var consecutive = true;

            var index = 0;

            while (index < checkedTimeslots.length - 1 && consecutive) {
                var currentTimeslot = checkedTimeslots[index].labels(0).innerText;
                var nextTimeslot = checkedTimeslots[index + 1].labels(0).innerText;

                var currentTimeslotEndTime = currentTimeslot.split("-")[1];
                var nextTimeslotStartTime = nextTimeslot.split("-")[0];
                if (currentTimeslotEndTime != nextTimeslotStartTime) {
                    consecutive = false;
            return consecutive;

IMPORTANT EDIT: “var currentTimeslot = checkedTimeslots[index].labels(0).innerText;” Doesn’t work in IE9!
Or atleast not for me. I got an error where the validation didn’t work in IE but worked in FireFox and Chrome. While debugging i found out the problem was that IE interpreted the checkbox as a DispHTMLInputElement rather than a HTMLInputElement as Chrome and FF did, and the Disp object did not have the labels attribute which I used to get the text value. A collegue of mine helped me solve the issue using a small piece of jQuery:

var currentTimeslot = jQuery('label[for=' + checkedTimeslots[timeSlotIndex].id + ']')[0].innerText;

Instead of directly getting the text, you get the label based on the value of its for-attribute, which is the same as the id of the checkbox. When we have the label we can easily get the innerText value from it. Now the solution works in IE9 aswell.

The third function simply checks if the user has selected the correct number of timeslots depending on the selection made in another control (a RadioButtonList).

function checkTimeslotsIfCorrectNumberOfSlots(checkedTimeslots) {
            var valid = false;
            var numberOfSelectedTimeslots = checkedTimeslots.length;
            var meetingTypeList = document.getElementById('<%=myRadioButtonList.ClientID%');
            var meetingTypes = meetingTypeList.getElementsByTagName("input");

            var selectedType;
            var index = 0;
            var checked = false;
            while (index < meetingTypes.length && !checked) {
                if (meetingTypes.item(index).checked == true) {
                     selectedType = meetingTypes.item(index);
                     checked = true;
            if (checked == false) {
                return true;
            if (selectedType.value == "Type1") {
                if (numberOfSelectedTimeslots >= 4 && numberOfSelectedTimeslots <= 8) {
                    valid = true;
            else if (selectedType.value == "Type2") {
                if (numberOfSelectedTimeslots >= 1 && numberOfSelectedTimeslots <=4) {
                    valid = true;
            return valid;

Javascript intellisense, SharePoint example

A colleague of mine gave me a great tip for adding intellisense for javascript when building your webpages. Simply add the following code to the page, inside the asp:content tag:

<asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible="false">
    <script type="text/javascript" src="file://fileLocation\fileName.js" />

Replace the src value to the scriptfile which contain the code you need. Below is an example which gives a lot of useful SharePoint intellisense-options when writing javascripts. I’m sure there are plenty of other good examples out there.

<asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible="false">
    <script type="text/javascript" src="file://C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\MicrosoftAjax.js" />
    <script type="text/javascript" src="file://C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\SP.Runtime.debug.js" />
    <script type="text/javascript" src="file://C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14 \TEMPLATE\LAYOUTS\SP.debug.js" />
    <script type="text/javascript" src="file://C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\SP.Core.debug.js" />
    <script type="text/javascript" src="file://C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14 \TEMPLATE\LAYOUTS\SP.Ribbon.debug.js" />