简体   繁体   中英

Adding src attribute to <script>

I have this:

script_url = 'http://externaldomain.com/script.js'
div_id = 'div'+Math.floor(Math.random() * 1000000);
document.write('<div id="'+div_id+'"><scr'+'ipt id="banner-to-load"></scr'+'ipt></div>')

After DOM is ready i do this:

$('#banner-to-load').attr('src',script_url)

Now, script_url appended, but nothing happens. External script has some functions and document.write , but they don't work. How can i run external script? Or if i run it document.write inside will rebuild my already compiled DOM?

The src attribute is not loaded asynchronously. Load your js with ajax

$.getScript(); or $.ajax({url:source, dataType: "script"});

Have a look here http://api.jquery.com/jQuery.getScript/

Try setting src before you add it and recheck your script_url.

document.write('<div id="'+div_id+'"><script '
  +'id="banner-to-load" src="' + script_url + '"></scr'+'ipt></div>')

Update : Or make a cross domain Ajax Query. If you control the other page you can allow cross domain queries by setting the " Access-Control-Allow-Origin " header.

尝试将banner_to_load附加到body对象

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