RSS
 

JavaScript Video Embed Widget

06 Apr

Overview | Inserting the Widget | Name Collision | Dynamic <script> Loading
Cross-Domain Scripting and XMLHttpRequest | In Conclusion

Overview

At VideoSift we have always made available the embed code for every video on the site. Until now, the provided code has just been the raw <object> and <embed> tags as you would acquire directly from the video host, but we wanted to provide a much more attractive embed.

We opted to achieve such a thing by providing users with a <script> tag that builds the fancy new widget into the DOM of the host page. Initially, the plan was to just generate a pretty simple DOM structure wrapped around a video, but it evolved from there to include:

  • the ability to optionally start out as a thumbnail image that when clicked will expand into the full widget
  • a functional vote button that would remotely cast an up-vote for logged in members
  • a brief, scrollable listing of comments on the video

There were a few interesting issues that needed to be resolved along the way:

  • Where on the host page should the widget be inserted?
  • What happens if the host page contains multiple widget <script> tags?
  • How should we dynamically load the widget in comments on VideoSift?
  • How should we cast votes on remote host pages that need to be posted to VideoSift?

Inserting the Widget

When it came to inserting the widget into the DOM of the host page, the desired location was obvious: immediately adjacent to the <script> tag itself. Really the only issue was to locate the appropriate <script> tag.

We start by searching for the target node in the DOM tree for all nodes with tagName ‘script’ and examine their “src” attribute:

function createWidgetDiv() {
  scripts = document.getElementsByTagName('script');
  for (i=0; i < scripts.length; ++i) {
    if (/videosift\.com\/widget\.js\?.*video=123456(&|$)/.test(scripts[i].src)) {
      widgetdiv = document.createElement('div');
      scripts[i].parentNode.insertBefore(widgetdiv, scripts[i].nextSibling);
      break;
    }
  }

// now we can start inserting our widget contents into widgetdiv
}

Name Collision

At this point we discover another issue. How are we sure this <script> tag belongs to the widget that’s currently executing? The user could have inserted onto the host page two <script> embeds. We handle the issue of there being two different embeds on the same page by checking if the <script> src URL contains the video ID that we’re currently executing with. We do not, however, handle the situation where a user inserts two embeds for the exact same video ID. In that case, both the first and the second widget will insert themselves after the first <script> tag because it’s the first one encountered in the DOM tree.

This brings us to the related issue of variable and function name collisions shared by multiple embedded scripts. With just a single widget on the page, we wouldn’t have to worry about naming convention, but let’s say we have two widgets with video IDs 111 and 222 both on the same host page. When the widget for 111 executes, everything will be fine, but when 222 executes, it will define a new createWidgetDiv(). If after that happens 111 calls createWidgetDiv() again, it will then be calling that defined by 222.

One way to fix this is to define the functions with a video ID specific suffix, e.g., createWidgetDiv_111() and createWidgetDiv_222(). This is not ideal, however, because considering again the situation where the host page contains two widgets with the same video ID, there will again be overlap. So, I opted to append a random number to every important function and variable name like createWidgetDiv_3948717().

Dynamic <script> Loading

So far, so good. At this point a page can load with any number of widgets already embedded in the HTML, but uh oh- what happens if we try to insert a <script> tag into a page that’s already been loaded? When we decided to modify VideoSift comment listings to allow just our special <script> tag, we needed to adjust how we loaded it. Here’s a very simple example trying to insert a <script> tag with jQuery:

$("#some_div").html('<script type="text/javascript"
  src="http://videosift.com/widget.js?video=111"></script>');

This won’t work because the <script> tags won’t be parsed. (This is not just jQuery-specific.) The fix, unfortunately, is not an issue that can be dealt with in the widget itself, but by the host page that is loading the script. Rather than attempting to insert a script tag, you’ll have to manually manipulate the DOM to insert a node with tagName ‘script’. You could use a function along these lines:

function dynScript(src) {
  script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = src;
  return script;
}

// insert it somewhere
$("#some_div").append(dynScript('http://videosift.com/widget.js?video=111'));

Cross-Domain Scripting and XMLHttpRequest

The final piece of the puzzle was getting the vote button to function when the widget is hosted on a remote domain. For security, XMLHttpRequest/Ajax requests are disallowed from communicating with scripts on foreign websites.

We clearly want to allow VideoSift users to cast votes for videos embedded on external sites, so we used a common workaround for the cross-domain restriction and inserted a dynamic script tag into the DOM specifying the vote URL as the <script> src attribute.

If that sounds familiar, yep, you guessed it. We reuse the dynScript() function for this purpose and it works splendidly. For example, we can do something like this:

$("#vote_btn").click(function(){
  // normally we'd make an Ajax request here, but not this time
  $(body).append(dynScript('http://videosift.com/widget_vote.js?video=111'));
  return false;
});

And the loaded script can take care of the post-processing for the host page that would normally happen in the Ajax callback. For example:

if (voting_failed)
  alert('Could not cast your vote!');
else
  updateVoteButton();

In Conclusion

Well, that’s it for my very first clog post. I hope most of what I wrote up there isn’t too vague to be appreciated by anyone who might be looking for some guidance or answers. My intent was to provide in broad strokes a breakdown of the wrinkles encountered on this project and how they were ironed out.

Here is an example of the widget in action.

The embed code for this widget follows:

<script type="text/javascript"
  src="http://videosift.com/widget.js?video=170447&width=540&comments=15&minimized=1"></script>

 

80,575 views

Tags: , , , , ,

Leave a Reply

 

 
  1. dag

    April 8, 2010 at 5:10 am

    This is a really nice template.

     
  2. rommel

    April 8, 2010 at 9:17 pm

    Yeah, there are a few nice themes I’ve found, but there’s something really appealing about this one.

     
  3. Dynamic Facebook and Tweetmeme Widgets « Rommel Santor's Clog

    April 9, 2010 at 1:19 pm

    […] presented a couple of problems because, similar to an issue touched on in my last clog, the widgets needed to be inserted dynamically and that’s usually easier said than done. […]