Gem of the day

It’s not like I’m going to post a random thing I found useful as a Gem-of-the-day every day, but let’s stick with often.

The first gem is this one:

/**
 * Execute a script in the global scope.
 *
 * @param {String} str
 * @type  {String}
 */
jpf.exec = function(str){
    if (!str) return str;
    var head, script;
    if (window.execScript) {
        window.execScript(str);
    } else if (head = document.getElementsByTagName("head")[0]) {
        script = document.createElement('script');
        script.setAttribute('type', 'text/javascript');
        script.text = str;
        head.appendChild(script);
        head.removeChild(script);
    } else {
        eval(str, window);
    }
    return str;
};

So what does this little gem do? Well, it provides a developer the power to execute a piece of script - at runtime of course - in the global scope. For example, if your XmlHttpRequest loads the content of a .js script file (e.g. the Content-type header is set to ‘text/javascript’), ‘exec()’ will execute that script as if it were loaded with a <script> tag in the <head> section.

Dynamic script loading this feature is called. Wow. Anyway, we use it at Javeline and I found it in the Mootools library - lots of cool stuff in there by the way.

Update: Added the eval fallback with its second argument telling eval to execute the code in the scope of the window object. (This is supported by Gecko browsers only)
Update2: Changed document.head reference to document.getElementsByTagName(”head”)[0]. (Thx Mors)

1 Responses to “Gem of the day”


Leave a Reply