Archive for the 'javascript' Tag

  1. Problems having a simple, self-contained script with dependencies

    A while back I was working on a javascript based video solution, and I wanted to make it as simple as possible to include a video widget into a page. This would be roughly along the lines of…

       1: <script type="text/javascript" src="blah.js"></script>    
       2:  
       3: <script type="text/javascript">
       4:     
       5:     mycompany.video.addVideoWidget({
       6:         siteId: "Heat",
       7:         keywords: "Britney Spears",
       8:         parent: "Id of the container"
       9:     });
      10:     
      11: </script>

    When authoring a script like this, it needs to be entirely self-contained as you have no knowledge of what other scripts have been included on the host page, or what versions etc.

    The issue is how to offer this script when you have a dependency. In this case I wanted to use swfoject as a reliable way to add a flash movie to a page. Another common scenario would be writing script on top of jquery. An example is Typekit who end up packaging up and distributing jquery as part of the code they require you to download – discussed here.

    Given that you have no working knowledge of the host page, the only possible option is to package up the dependency, avoid naming conflicts, and include it with your script logic. However this seems quite wasteful given that the host page may also include the same library.

    We are so used to using libraries now to make javascript a pleasurable activity, the idea of writing raw script, while possible, is really not an enjoyable prospect.

    I don’t have a good answer to the problem – I ended up going down the same route that Typekit have gone. The only other option is to provide a flavour which requires the host page to implement the dependency, but then you lose the simplicity and are open to tricky issues around versioning.

    Still, I guess life is short and bandwidth is cheap.

    Posted at 4:37 pm on 16/12/09

    Tags: ,

    Comments: None

  2. Problems with javascript minification that affects SwfObject 2.1 in Internet Explorer

    This is actually a more general issue with javascript minification that can affect a number of scripts, but I noticed it while tracking down weird behaviour with the minified version of SwfObject that only affected Internet Explorer.

    Basically, standard behaviour with most javascript minifiers is to strip out anything contained within comments. I finally tracked down this piece of code in the swfobject library that was getting stripped out (incorrectly) by the minifier…

    /*@cc_on
    ie = true;
    @if (@_win32)
    windows = true;
    @elif (@_mac)
            mac = true;
        @end
    @*/

    This library carries out browser detection by using the proprietary Conditional Compilation feature in Internet Explorer. In order to stop other browsers from choking, the code is wrapped in a comment.

    I’m not commenting whether this is a good or bad idea, simply that it does appear in existing scripts, and causes a bunch of javascript minifiers to strip out functional code.

    I think my approach will be to revise the set of regular expressions that control what gets stripped out to cater for this variation.

    Posted at 12:01 pm on 26/03/09

    Tags: , ,

    Comments: None

  3. Webtrends tracking from Flash

    I’ve been working on a Flash widget, and the majority of the sites it will be hosted on use WebTrends for analytics. I recently had to look into capturing certain interaction events from the Flash movie and passing them through to WebTrends for reporting.

    Flash events are tracked as fake page impressions in WebTrends based on unique URLs that you define. The flash movie doesn’t talk to WebTrends directly - it calls through to javascript on the host page which logs the event via standard WebTrends javascript.

    In my case I’m working on a widget that could be hosted on a variety of pages that may or may not implement WebTrends. The required behaviour is for tracking to automatically kick in if the host page implements WebTrends, but gracefully degrade if not. I have a javascript file that handles interaction with the flash movie, so I can guarantee certain js functions exist on the host page.

    The solution looks like so…

    Add an ActionScript class to pass events through to host page

    package {
    
    
        import flash.external.ExternalInterface;
    
    
        public class Analytics {
    
    
            public static const WIDGET_LOADED:String = "/Video/Widget/WidgetLoaded";
            public static const PLAYER_LAUNCHED:String = "/Video/Widget/PlayerLaunched";
    
    
            public function Analytics(): void {
            }
    
    
            public static function captureEvent(eventType:String) {
    
    
                if (ExternalInterface.available) {
                    ExternalInterface.call("mycompany.video.captureAnalyticsEvent",  eventType);
                }
            }
        }
    }

    An example of passing an event to this class…

    Analytics.captureEvent(Analytics.WIDGET_LOADED);

    Implement javascript functions on the host page

    /* set up namespace for new functions */
    if (window["mycompany"] == null) {
        window["mycompany"] = {};
    }
    
    
    mycompany.video = {
    
    
        webtrendsTrackingFunction: {},
    
    
        captureAnalyticsEvent: function(eventType) {
    
    
            var uriParam = 'DCS.dcsuri';
    
    
            if (typeof (this.webtrendsTrackingFunction) == 'function') {
    
    
                // if user has nominated a specific tracking function
                this.webtrendsTrackingFunction(uriParam, eventType);
            } else if (window["dcsMultiTrack"] != null) {
    
    
                // if dcsMultiTrack already implemented on page
                window.dcsMultiTrack(uriParam, eventType);
            } else if (window["dcsTag"] != null) {
    
    
                // otherwise if webtrends implemented on page, use default implementation
                mycompany.video.analytics.dcsMultiTrack(uriParam, eventType);
            }
        }
    }
    
    
    mycompany.video.analytics = {
    
    
        dcsMultiTrack: function() {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i].indexOf('WT.') == 0) {
                    WT[arguments[i].substring(3)] = arguments[i + 1]; i++;
                }
                if (arguments[i].indexOf('DCS.') == 0) {
                    DCS[arguments[i].substring(4)] = arguments[i + 1]; i++;
                }
                if (arguments[i].indexOf('DCSext.') == 0) {
                    DCSext[arguments[i].substring(7)] = arguments[i + 1]; i++;
                }
            }
            var dCurrent = new Date();
            DCS.dcsdat = dCurrent.getTime();
            dcsTag();
        }
    }

    The key points above the script above…

    • To report events from Flash, WebTrends require an additional function on the host page that they provide - dcsMultiTrack
    • If the host page has implemented dcsMultiTrack already, the existing function will be used
    • If the host page implements standard WT js but not the additional function, a fresh implementation of the dcsMultiTrack function will be used
    • If WebTrends javascript has not been implemented on the host page, nothing bad happens

    In addition, we have a standard function that the flash movie will always call, so if we need to extend functionality to cater for different analytics systems etc, then we have a single place to implement this.

    This is probably the least sexy post I’ve ever written, but it seemed worthwhile to document this. I’ll follow up with some sexified content sometime soon.

    Posted at 12:07 pm on 27/02/09

    Tags: , , ,

    Comments: 2

  4. Using ExternalInterface to call Javascript from Actionscript - ‘null’ is null or not an object in IE

    If you are using ExternalInterface in Actionscript 3 to call through to a javascript function, the original object tag that instantiated the flash runtime needs to have an explicit id attribute. Otherwise you’ll get the above error when running the movie in Internet Explorer.

    Posted at 11:00 am on 26/02/09

    Tags: ,

    Comments: 11

  5. Added object tag to page via DOM methods - IE chaos

    I’ve been working on a widget project that involves Flash and Javascript, and came across some very strange behaviour in IE6 / 7. The object tag to render the flash movie is dynamically added to the page at runtime using standard DOM methods - document.createElement, setAttribute, appendChild etc. Life was wonderful until I opened Internet Explorer, which hangs with what looks like a request for a file with no timeout (progress bar moving very slowly but never completing). This is identical behaviour to how IE behaves when the location of the SWF is invalid.

    The markup

    The markup I was generating was based on Flash Satay. Including this as static markup in a page works fine. Simple example below…

    <object type='application/x-shockwave-flash' data='test.swf' width='420' height='155'>
        <param name='movie' value='test.swf' />
    </object>

    DOM approach that chokes IE

    The following approach causes IE to choke…

    <script type="text/javascript">
    
    
        var object = document.createElement('object');
        object.setAttribute('type', 'application/x-shockwave-flash');
        object.setAttribute('data', 'test.swf');
        object.setAttribute('width', '100');
        object.setAttribute('height', '100');
    
    
        var param = document.createElement('param');
        param.setAttribute('name', 'movie');
        param.setAttribute('value', 'test.swf');
        object.appendChild(param);
    
    
        document.body.appendChild(object);
    
    
    </script>

    The solution / workaround

    For some reason if the object tag + params are parsed at the same time everything works fine, so the solution involves using the alternate approach to manipulating the DOM - innerHTML. This wouldn’t have been my first choice given the situation, but it seems to be the only way to get this working. A version that works in IE…

    <script type="text/javascript">
    
    
        var fragment =
            "<object type='application/x-shockwave-flash' data='test.swf' width='100' height='100'>" +
                "<param name='movie' value='test.swf' />" +
            "</object>";
    
    
        var container = document.createElement('div');
        container.innerHTML = fragment;
        document.body.appendChild(container);
    
    
    </script>

    This achieves the same end result - a DOM element node that can be inserted anyway you wish, but avoid the problem in IE.

    Posted at 10:51 am on 26/02/09

    Tags: , , , ,

    Comments: 2

  6. Simulated Events and Firefox

    Suppose you want to write some javascript to simulate an event taking place. For many of the common events, there is the equivalent method, so you can call click() on an element to simulate a mouse click. After a painful debugging session today I found that doing this in Firefox means that the wrong element ends up on the event.target property, which can cause various problems when you’re handling the event.

    In this case I had an input element that was kicking off an ansychronous form submit when clicked. On top of this I’m implementing drag and drop behaviour, so I figured it would be as simple as simulating the click event when the item was dragged and dropped in the right way. The click handler already worked, and kicked off the async operation as desired, so it should be a nice layer on top.

    The async operation basically hijacks the form submit if it is caused by certain elements, and performs an async post instead. The problem with the event target in Firefox meant that this behaviour never kicked in.

    A workaround was to use dispatchEvent instead. This allows a simulated click which results in the correct event target set. This is in the W3C DOM level 2 spec, and is implemented in Firefox (but not IE).

    Posted at 6:17 pm on 19/06/07

    Tags: , ,

    Comments: None

  7. Javascript New Releases

    There are a couple of new books that are worth taking a look at. The first is the O’Reilly book on Atlas. I’m currently reading this one from APress, but I’ve heard rumour that the OReilly book provides much more context in examining the underlying technologies that Atlas is based on.

    The other is one that I’ve been looking forward to for a little while now, PPK on Javascript. This comes from the guy behind quirksmode.org and should be an interesting read. It’s along a similar direction as DOM Scripting but providing the next level of detail, where DOM Scripting was a great introduction into modern use of javascript and the DOM. My copy should be delivered midweek, so I’ll let you know how I get on with it.

    If javascript makes you feel sad or confused and you need a little light relief, you should come along to Stephen K Amos at the Garrick theatre on Thursday (I have no idea about ticket availability - currently assuming we can get some for thurs). I’ve been to a couple of shows in Edinburgh which made my face hurt from laughter. I’m eager for more face-ache, so should be going this week too.

    Posted at 9:37 am on 23/10/06

    Tags: , , , ,

    Comments: None

  8. Atlas or YUI?

    For a little while I’ve been meaning to take a proper look at Atlas, Microsoft’s main offering to help out in building AJAX applications and richer web based interfaces.

    Javascript is definately back in fashion, with a number of libraries popping up to help out with application development. I think overall this is fine, so long as you have an appreciation of what is actually happening under the scenes. I don’t think a library should dictate the way that you build an application, rather enable you to build it more efficiently.

    I’ve started using elements of the Yahoo YUI library which is very impressive. There seem to be a lot of very useful little utility functions available, the kind of thing that you would typically rewrite on each project.

    I’m quite curious about how the Microsoft and Yahoo libraries compare. I’ll post some information about this when I’ve had a chance to look in more detail at Atlas.

    Posted at 12:16 pm on 3/07/06

    Tags: , , , ,

    Comments: None

  9. PPK on Javascript

    Peter-Paul Koch is publishing a new book on Javascript. If you have been following the work of Jeremy Keith, chances are you’ve come across his book which is one of the best modern web development books I’ve read. This looks like it extends the same ideas, but goes into much more technical detail.

    It’s not out just yet, but worth keeping an eye out for - I think the UK release is towards the end of August.

    Posted at 11:34 am on 28/06/06

    Tags: , ,

    Comments: None

  10. Yahoo UI library

    I’d heard a number of people mention various different javascript libraries recently. Seeing a discussion panel talking over the pros and cons of using libraries, and the main ones in development finally prompted me to have a nose around a couple. In particular Simon Willison was promoting the work that Yahoo have been doing recently in publishing a free, open source library that they use internally to build the various Yahoo sites and applications.

    I have to say I’m seriously impressed with the work they have done. A lot of the ideas are pretty simple, but the kind of thing that you write from scratch on each project when it’s needed. However, in this case it’s had a load of development and cross browser testing effort thrown at it.

    Some of the methods on their DOM object are extremely useful - things like getting the viewport dimensions, or getElementsByClassName. In addition, the library that covers event handling provides a number of very practical features that you could start using immediately.

    I am naturally a little sceptical about this kind of thing - I think it’s very important to understand the core technologies that a framework is based on. However these libraries provide the kind of work that you would code yourself, but in a tidy, useable, documented package.

    There will be a slight hit on bandwidth, but the library is split into different modules, so you should be able to take what you need without too much extra.

    I’ll certainly consider using this on future projects.

    Posted at 12:40 pm on 26/06/06

    Tags: , ,

    Comments: 3