0

How can an external javascript file be injected into a div. When I try to set it using below code, the div 'toupdate' is not updated with new javascript file.

<script type="text/javascript">

$(document).ready(function () {
      $('#toupdate').html('<script type="text/javascript" charset="utf-8" src="http://static.polldaddy.com/p/5968383.js"></script>');
});

</script>

    <body>
    <div id="toupdate">
    <script type="text/javascript" charset="utf-8" src="http://static.polldaddy.com/p/6343621.js"></script>
    </div>

    </body>

2 Answers 2

1

Your replacement code is being executed before the div 'toupdate' has loaded, you either need to move the <script> tag to after the div or put you replacement code within a $(document).ready() function like so:

$(document).ready(function () {
  $('#toupdate').html('<script type="text/javascript" charset="utf-8" src="http://static.polldaddy.com/p/5968383.js"></script>');
});

EDIT:

tested and working example:

$(document).ready(function() {
    $('#toupdate').children('script').attr('src', 'http://static.polldaddy.com/p/5968383.js');
});​

JSfiddle: http://jsfiddle.net/m7q3H/45/

Sign up to request clarification or add additional context in comments.

1 Comment

it seems to be loading the new javascript but not updating the UI.
1

you could use the $.getScript("URL") function definition

2 Comments

can that function be used to inject the script into a div ?
Im not entirely sure if it can be, there is a callback function with it that will run after the script has successfully been downloaded, but it seems the script will already have been run at this point. sorry i cant be of more help.

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.