Wednesday, December 15, 2010

Script Block Type and Dynamic Script Loading

Obviously I haven't written in a while, but after spending a few debugging hours on this simple issue I hope to save somebody some time.

I am re-writing a widget framework for a client so that all widgets are loaded dynamically client side after page load. Widget content may be complex and include all manner of scripting.

I was having problems getting javascript blocks in the dynamically loaded content to execute in any other browser than Firefox. I was also seeing some blocks execute in the other browsers, but not all and couldn't figure out what was special about the syntax, methodology, or source of those that would work.

I finally figured out that it was the 'type' attribute on the script blocks themselves. We had some script tags with 'ecmascript' and others with 'javascript'. The 'ecmascript' type is not dynamically executed by webkit browsers, or IE; 'javascript' type blocks are. This includes omitting the type attribute altogether as these browsers assume javascript when not otherwise indicated.

Perhaps this script type exclusion is well documented somewhere, but most discussions surrounding problems loading scripts dynamically center on getting around same source issues. Here it is simply a matter of type.

Take home point: always indicate 'text/javascript' if you include the type attribute.

You can test for yourself with the code below. Change the type in the content page to see the background behind 'HI' turn red in browsers other than Firefox.

Simple script loading page...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<script type="text/javascript" src="//"></script>
<script language="javascript" type="text/ecmascript">
    $(document).ready(function() {
<div id="target">
Simple Content Page:
<script type="text/ecmascript">

    $("#test").css("background-color", "red");
<div id="test" style="height:20px;width:20px;">

Submit this story to DotNetKicks

No comments: