javascript - trick to evaluate javascript code in global scope

the reason why we have a dedicated session to have the tick to evaluete some javascript code inthe global context is that "The built-in methods for code evaluation are spotty, at best."

 

 It is a prooven practise , so that it is also a fool-proof way to execute code in the global scope, across all browsers , is to create a fresh script element, inject the code you wish to execute inside the script, and then quickly inject and remove the script from the document. 

 

 

below shows the method that demonsrate this technique 

 

 

/**************************************
*@Summary
*  this code is about to execute the script in the global context.  
*
* 
* the built-in methods for code evaluation are spotty, at best. THe one fool-proof way to execute code in the global scope, across all browsers, is to create a fresh script element, inject the code you wish 
* to execute inside the script, and then quickly inject and remove the script from the document.
* 
* this trick turns out to be very effective across many browsers.
*
*
***************************************/

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;
    header.insertBefore(script, head.firstChild);
    head.removeChild(script);
  }
}
 

 

Though I am not quite familiar with the JQuery libraries, but I think you can use the following code to dynamically load and executing some code on demand(the code may be downloaded fromthe server)\.

 

 

/**
* @Comment
*  the code below shows the possible way to do the 
*/
function evalScript(elem) {
  if (elem.src) {
    jQuery.ajax({
      url: elem.src,
      async: false,
      dataType: "script"
    });
  } else {
    jQuery.globalEval(elem.text || "");
  }
  if (elem.parentNode)
     elem.parentNode.removeChild(elem);
}
 

 

 

 

你可能感兴趣的:(JavaScript)