Reputation: 4849
I am loading the JS file using javascript:
window.onload = function() {
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", "js/index.js")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
the index.js file has the following line
document.write('<a href="#" target="_blank">link</a>');
I am sure the file loads ( tested with an alert()) but for some reason the anchor is nowhere to be found on my page. There does not seem to be any js errors either.
the same line if included in the page directly works fine
FYI : this JS is for a plugin which will be cross domain installed. I am aware that the could be limitations there but would appreciate any guidance. Thank you
Upvotes: 1
Views: 542
Reputation: 15291
document.write isn't what you want to use here as it's more suited to inline JS (JS in your HTML document). Could you not write the hyperlink to the DOM using .innerHTML
(making sure that the element you wish to modify the innerHTML is loaded)?
https://developer.mozilla.org/en/DOM/element.innerHTML
Upvotes: 1
Reputation: 1073968
document.write
is really only useful for scripts that are executed inline with the parsing of the page. If you call document.write
later, it implicitly does a document.open
, which wipes out the page's content. I'm not sure why you're not seeing that, given what you've described.
When adding content after the initial page load, one uses the DOM, e.g.:
var a = document.createElement('a');
a.innerHTML = "link";
a.href = "#";
a.target = "_blank";
document.body.appendChild(a); // Or, of course, append to something more targeted
In terms of loading scripts cross-domain, there's no problem with that at all. What you're doing is fine, although you can shorten it a bit and it's best not to rely on the horror that is JavaScript's automatic semicolon insertion:
var fileref = document.createElement('script');
fileref.src = "js/index.js";
document.documentElement.appendChild(fileref);
There's no need for type
(JavaScript is the default), and src
is a reflected property (as is type
, if you do want to go ahead and use it). There's no need to append scripts to the head
element, anywhere in the document element (html
) is fine.
Upvotes: 3