0

How to load a javascript function via string

<div id="test_div">display here</div> // < --display here


<script type="text/javascript">

// string 
var _script=("<script type=\"text/javascript\">

    var disqus_shortname = 'example'; 
    (function () {
        var s = document.createElement('script'); s.async = true;
        s.type = 'text/javascript';
        s.src = 'http://' + disqus_shortname + '.disqus.com/count.js';
        (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
    }());
</script>");


// write/output the string
document.getElementById('test_div').innerHTML= _script;
</script>
6
  • dont think it will work and why do you wanna do this??? Commented May 4, 2011 at 12:45
  • 1
    w3schools.com/jsref/jsref_eval.asp Commented May 4, 2011 at 12:45
  • What are you trying to do? Do you want the code to run? Or do you want it to display in that div? Commented May 4, 2011 at 13:02
  • @ yes i want to run this code, Does not even show the messagebox document.getElementById("test_div").innerHTML = ("alert(\".\");"); Commented May 4, 2011 at 13:04
  • @Power-Mosfet: If you want to run that script block, just put it in the page, why is it a string? Commented May 4, 2011 at 13:11

2 Answers 2

1

JavaScript does not allow new lines inside strings, you need escape each new line with a \.

var _script=("<script type='text/javascript'>\
    var disqus_shortname = 'example';\
    (function () {\
        var s = document.createElement('script'); s.async = true;\
        s.type = 'text/javascript';\
        s.src = 'http://' + disqus_shortname + '.disqus.com/count.js';\
        (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);\
    })();\
</script>");
Sign up to request clarification or add additional context in comments.

Comments

0

Using jQuery

$('#test_div').click(yourFunctionName)

You need to name your function in the script

<script type="text/javascript">

// string 

var _script=("<script type=\"text/javascript\">

var disqus_shortname = 'example'; 
(function yourFunctionName () {
    var s = document.createElement('script'); s.async = true;
    s.type = 'text/javascript';
    s.src = 'http://' + disqus_shortname + '.disqus.com/count.js';
    (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
}());


</script>");

I assumed you meant that if you click on the testdiv it should do the function?

Or -- Did you mean you want to load the script dynamically into your webpage?! Ahhhh OK!

Using jQuery Again.

$(body).append('<script type="text/javascript">' + YOUR_JAVA_STRING + '</script>');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.