开发者

Javascript difference between eval() and appending script tags

开发者 https://www.devze.com 2023-02-08 11:09 出处:网络
I was wondering if someone could explain the difference between using Javascript\'s eval(), and another approach, like using JQuery to create script tags and then appending that element to the page:

I was wondering if someone could explain the difference between using Javascript's eval(), and another approach, like using JQuery to create script tags and then appending that element to the page:

eval(somecode);

vs.

$("<script type='text/javascript'>"+somecode+"</script>").appendTo("head");

Not sure if this is relevant, but here's the context: I'm working with a version of the Drupal Popups module whose basic purpose is to easily turn regular links into popups by AJAX'ing an entire page request and appending it to the page in a modal w开发者_如何学运维indow. This frequently includes external CSS and Javascript files. In an effort to improve the performance of all this AJAX loading I switched over to use AJAX queueing, and I changed an eval() of external scripts into the alternative listed about. However, that caused sporadic Javscript bugs on various other pages.


Well one (as far as differences go) is eval will return the result of an expression.

var result = eval('3+4'); // result = 7 

As long as your javascript string is in the structure of a script block, i would suggest injecting it within a script tag/


Adding script tags will load the scripts synchronously, whereas loading when you eval text via XHR, that was loaded asynchronously. Because of the async, the scripts were probably loaded out of order.

Note there are a billion if-but-then cases to this, but I'm guessing this is the case based on your scenario.

Now, you could load the XHR synchronously, but then things will drastically slow down. Browsers can load six (ish) scripts at once but execute them in order. The XHR will load one at a time.


I strongly suggest using JSON-P.

Add a callback function name on the outgoing AJAX request by creating a script node on the fly (with src=[url]), and let the callback function get called with json data. You define the callback function in your page (properly namespaced) and put your update logic inside it.

The advantage of dynamic script node callback is that there is no same-domain restriction like in XHR.

For example, your site is www.foobar.com and some webservices are hosted on www.foobarapi.com. you create a script node in runtime with src="http://www.foobarapi.com/baz?a=foo1&b=foo2&callback=foo.bar.baz"

Meanwhile in your page, you have:

foo.bar.baz = function(data) {
  // use the data
}

And your backend service, say a php, can look like:

$a=$GET['a'];
$b=$GET['b'];
$callback = $GET['callback'];
$c = someCalc($a, $b);
echo $callback . "({ \"c\" : $c });";
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号