Run script tags loaded by ajax

General question

Say you have a simple ajax request, for example $("#container").load('/url #content'); . A loaded DOM will be something like

 <a>email</a> <script>/* some script */</script> 

What can I do to get the contents of script tags?

Specific question

Cloudflare automatically protects email addresses in the DOM, replacing text with [email protected] and including a script that will solve it. However, the contents can be loaded asynchronously, and the script that does the untangling will not be executed. I could just disable the email protection feature (I think), but I'm wondering if there is another way.

Example

Look at the action at http://aysites.com/what - click "Contact"

+4
source share
3 answers

There is a pure js function that calls the JavaScript compiler. This is eval . You must use it.

Examples:

 jQuery.globalEval("var newVar = true;") 

on jQuery.com

Or

 eval("x=10;y=20;document.write(x*y)"); document.write("<br />" + eval("2+2")); document.write("<br />" + eval(x+17)); 

on w3schools

+3
source

My answer also includes some Tooraj magic.

Basically, we will use the same load function, and in the callback we are going to grab the script, take the functions from the inside, and then test them.

 $("#container").load('/url #content', function(){ eval($('#container script').html()); }); 

using the selector above and capturing the HTML from this selector (which, as it turned out, are functions in the script), we can then eval to execute this function and run it.

This is where jsFiddle works.

+2
source

you can put only part of the script on the page with the appropriate headers, and then use $.getScript() to get and execute the script,

See Doc: http://api.jquery.com/jQuery.getScript/

+1
source

All Articles