document.write Not working when loading external Javascript source
I'm trying to load an external JavaScript file dynamically into an HTML element to preview an ad tag. The script loads and executes but the script contains "document.write" which has an issue executing properly but there are no errors.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
source = 'http://ib.adnxs.com/ttj?id=555281';
// DOM Insert Approach
// -----------------------------------
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', source);
document.body.appendChild(script);
});
</script>
</head>
<body>
</body>
</html>
I can get it to work if
I don't have the ability to modify the script since it being generated and hosted by a 3rd party.
Does anyone know why the document.write will not work correctly? And is there a way to get around this?
Thanks for the help!
Another solution is to create an iframe, then load the script inside that iframe when the ajax call is ready:
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
var doc = iframe.contentWindow.document;
// do this whenever you want (f.ex after ajax is made):
doc.open();
doc.write('<script src="http://ib.adnxs.com/ttj?id=555281">x3C/script>');
doc.close();
That way, the document.write
in the end script will not affect your site, just the iframe. You will need to style the iframe to fit the ad.
It would be potentially dangerous to load an external script tag asynchronously if it also contains document.write
. So I would suggest either using document.write
at your end as well:
document.write('x3Cscript src="http://ib.adnxs.com/ttj?id=555281">x3C/script>');
Or just a script tag (duh):
<script src="http://ib.adnxs.com/ttj?id=555281"></script>
You do not want document.write
on $(function()
( when dom is ready )
Remove the document .ready
wrapper.
And move your to - before </body>
. ( or to the container location - where you want the widget to appear.)
so :
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
</head>
<body>
//bla bla...
<script type="text/javascript">
(function (){
var source = 'http://ib.adnxs.com/ttj?id=555281';
// DOM Insert Approach
// -----------------------------------
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', source);
document.body.appendChild(script);
})();
</script>
</body>
</html>
Important :
链接地址: http://www.djcxy.com/p/47908.html上一篇: 在ng中动态加载模板