3

I'm attempting to load the excanvas polyfill in the page-specific js file for my page. This script file is inserted after the body tag on my page.

The odd bit is that if I use

<script type='text/javascript' src='/Scripts/polyfills/excanvas.compiled.js'></script>

in my head tag, everything works great, but I don't necessarily want to load this script for HTML5 compliant browsers if I don't have to.

So naturally I tried to use Modernizr to load it selectively. This is my perfectly executing, but non-functioning javascript code:

<!-- language: lang-js -->
$(function () {
    Modernizr.load({
        test: Modernizr.canvas,
        nope: '/Scripts/polyfills/excanvas.compiled.js',
        complete: function () {
            setImage();
        }
    });

});

This seems to work fine. The excanvas script appears to load successfully. The setImage function creates the canvas element dynamically and adds it to a div on the page. This works fine in IE9 but fails to render in IE8.

<!-- language: lang-js -->
function setImage() {

    var canvasHello = document.createElement('canvas');
    canvasHello.id = 'canvasHello';
    $('#divContent').append(canvasHello);

    if (!Modernizr.canvas) {
        G_vmlCanvasManager.initElement(canvasHello);
    }

    var canvasContext = canvasHello.getContext('2d');
    canvasContext.width = 800;
    canvasContext.height = 600;
    canvasContext.fillStyle = "#000000";
    canvasContext.fillRect(0, 0, 600, 800);

    var img = document.createElement('img');
    img.src = '/Content/images/hello.png';
    img.onload = function () {
        canvasContext.drawImage(img, 100, 25, 100, 100);
    }
}

Did I miss something or does the excanvas script not function outside of the head tag?

Paul Irish
  • 47,354
  • 22
  • 98
  • 132
shinyhat
  • 31
  • 4

2 Answers2

2

in the given requirement you could use the IE conditional statements like this...

<!--[if lt IE 9]>
<script src="script/excanvas.js"></script>
<![endif]-->

would suffice....

the statement will only be understood by IE version less than 9 and the script tag gets attached.

sloth
  • 99,095
  • 21
  • 171
  • 219
0

The only thing you missed is the instructions on how to use excanvas:

The excanvas.js file must be included in the page before any occurrences of canvas elements in the markup. This is due to limitations in IE and we need to do our magic before IE sees any instance of in the markup. It is recommended to put it in the head.

Prestaul
  • 83,552
  • 10
  • 84
  • 84