It\'s considered good practice to use a self-invoking function to wrap strict mode compliant code, often called the strict mode pragma:
(function(){
\"use stri
Andrea Giammarchi has a nice technique for doing this, that works across browsers. Define a function in your self-invoking function called globalEval like so:
(function () {
"use strict";
function globalEval(data) {
data = data.replace(/^\s*|\s*$/g, "");
if (data) {
var head = document.getElementsByTagName("head")[0] || document.documentElement,
script = document.createElement("script");
script.type = "text/javascript";
script.text = data;
head.appendChild(script);
head.removeChild(script);
}
}
// use globalEval to stick variables into the global scope
globalEval("var myGlobal = 1;");
// myGlobal === 1
)();
// myGlobal === 1
Or define the globalEval function outside of the self-invoking code if you want to use it in other scopes.