jquery load script conflict
I'm using JQuery to append a script tag to a div, ex.:
开发者_Go百科$("#special_div").append("<script src="http://blablabla.com/id.php?id=0000"></script>");
and that script returns:
document.write("<object ....></object>");
but when I append it, all my HTML is gone and only that tag is written..
Can anyone tell me what's wrong?
Escape your quotes first of all:
$("#special_div")
.append("<script src=\"http://blablabla.com/id.php?id=0000\"></script>");
Additionally document.write is fine depending on when it is called.
Edit: removed other text, other answerer about document.write enlightened me on this :D Thanks @Ivo
Here is the explanation:
Any document.write statement that runs after the page finishes loading will create a new page and overwrite all of the content of the current page
What's wrong is that you're using document.write()
— or at least the author of that script is using it. That's what document.write()
does when it's called after the actual original document has been built by the browser. I suppose your code is in some jQuery initialization block:
$(function() {
// your code somewhere in here ...
});
Thus it runs only when the browser has gotten the page all ready. But at that point, a new call to document.write()
will be interpreted as meaning that you want to completely replace the current page with new stuff.
One thing to try would be to put an <iframe>
in the document (not with document.write()
!!) and then put the <script>
tag inside that.
The script that you load uses document.write
, but you're loading the script after the page has already been loaded completely, therefore document.write
will overwrite the contents of the page.
For more reasons against the use of document.write
see:
Why is document.write considered a "bad practice"?
To fix it, you need to include the script in the HTML source itself.
don't use document.write but appendChild to append the obejct tag
精彩评论