简体   繁体   中英

Append <script> into <div> using jquery

I'm trying to append a <script> tag into my <div> . Whenever I try to do this, the script just doesn't loads. But it works if I hard coded it under the tag.

But if I try to append an <img> tag, it works!

Here's a partial code to give you some ideas.

$(document).ready(function() {
    var tag = '<script src="xxx.js"></script>'; // file to grab images
    var tag2 = '<img src="some image link"></img>';
    $('#test').append(tag); //testing
    $('#test2').append(tag2); //testing
});

On HTML

<div id="test"></div> <!-- Not Working! -->
<div id="test2"></div> <!-- This Works! -->

<div id="test"><script src="xxx.js file to grab images"></script></div> <!-- This Works too! -->

Edit with more info below:

I've actually looked for solutions over the net and most of the answer are almost the same as the ones given here. In my case, it is slightly different from the others. That's because the tag variable is actually a must from database.

<?
$result = mysql_query("SELECT code FROM users_loc WHERE method='script'") or die(mysql_error());
$row = mysql_fetch_array($result);
?>

and on javascript side:

    $(document).ready(function() {
        var tag = <? echo $row['code'] ?>;
        var tag2 = <? echo $row2['code'] ?>;
        $('#test').append(tag); //testing
        $('#test2').append(tag2); //testing
    });

On my site, users will input their external image source into my database, and I will grab the source and display it on my site. But the problem arise when a user put in a <script> tag which works if it were hard coded into the <div>

I kept having this error message on my console "A call to document.write() from an asynchronously-loaded external script was ignored."

I hope this answers the confusions. Thanks.

Edit: I think this is the problem with append: Does Jquery append() behave asynchronously?

It all because about the parsing problem. The problem showing up after found </script> this code. It's assume we want to close the script tag but we won't. In order to avoid that, put \\ before / like so to escape special character :

$(document).ready(function() {
  var tag = '<script src="xxx.js"><\/script>'; // file to grab images
  var tag2 = '<img src="some image link"></img>';
  $('#test').append(tag); //testing
  $('#test2').append(tag2); //testing
});

DEMO

Try inspect the element in chrome to see the code.

Try it:

var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'xxx.js';

$('#test').append(script); 

If it matters where in the source order the script tag is injected, Mario Araque's solution is for you. If it does not matter, R3tep's solution does the job nicely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM