开发者

How to add a script at runtime? (document.write is not a function)

I trying to add a script to my Xul application at runtime, with:

document.write('<script type="text/javascript" src="chrome://myapp/content/myscript.js"/>');

but I got:

Error: document.write is not a function

The function does exist in the docs. I got also this example from the docs:

document.open();
document.write("<h1>Out with the old - in with the new!</h1>");
document.close();

but I got:

document.open is not a function

Any idea what's wrong?

--update

Maybe I could put my js code in a Javacript Module and import it with Components.utils.import (looking for where to put the resource and how to refe开发者_如何学JAVArence it)


The document.write function is not available if you are using XHTML; see: http://www.w3.org/MarkUp/2004/xhtml-faq#docwrite. It is likely that you are using XHTML.

You should evaluate whether you actually need to use XHTML. If not, then you will be able to use document.write. But if you do, you'll need to use an alternate approach to manipulating the DOM. You can do it directly using DOM methods, or you could use a helper library such as jQuery.


From this example.

Using the createElement method in XUL lets you accomplish things similar to document.write in HTML, with which you can create new pages and parts of a web page.


Do you have the javascript inside a script tag? And do you initiate the function somewhere in the code? It doesn't run it self.

This works:

<html>
<head>
<script type="text/javascript">
function addCont(){
document.open();
document.write("<h1>New text</h1>");
document.close();
}
</script>
</head>
<body onload="addCont()">
<p>Some text...</p>
</body>
</html>


You said in a comment on another answer that you were doing the document.write() in a function called from a setTimeout that itself was in the onload. I'd recommend against using document.write() after the page has loaded. According to the Mozilla doco:

an automatic document.open() call happens when document.write() is called after the page has loaded, but that's not defined in the W3C specification.

And because of the automatic document.open()

If a document exists in the target, this method clears it

From memory I thought older versions of IE just gave an error if you used document.write() after the page had loaded, but I can't be bothered trying to find anything in their doco.

And as somebody else mentioned, it doesn't work with xhtml.

Why do you even want to do the document.write() in this instance? Why not just include your script directly?


There are two ways to dynamically load a script at runtime.

The first way is via the subscript loader.

The second way is to create an overlay that loads your script and dynamically load the overlay.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜