Is There A Way To Use Document.write But Write To The Top Of The Body?
Solution 1:
If you can, avoid using document.write
. Here is a common way to insert a script, so that it gets executed:
document.addEventListener('DOMContentLoaded', function(){
var s = document.createElement('script');
s.src = "my_script.js";
document.body.appendChild(s);
}, false);
If you have any other HTML you'd like to add, you could use innerHTML
, but it's sometimes better to avoid using it, since it will replace all the elements (and maybe break some event listeners that were set before). Instead, you can use insertAdjacentHTML
. Note that if a script is added via this method, it will not be executed:
document.addEventListener('DOMContentLoaded', function(){
var code = '<style>.class{color:red}</style><div class="class">Hello</div>';
document.body.insertAdjacentHTML('afterbegin', code);
}, false);
You can choose where the code gets appended by using these options: beforebegin
, afterbegin
, beforeend
or afterend
.
Solution 2:
No, document.write writes the HTML in-line after the <script>
. but you could modify innerHtml
of the body element (or a <div>
placed at the top etc.), but you might have to wait for the HTML to load first.
Seeing as you can't edit the script. what you need to do is place the script call in a <div>
and use CSS to position the <div>
at the top. (or use inline javascript to reorder the html elements on the page) so that the <div>
is moved up to where you want it.
Solution 3:
Do not use document.write
nor reparse the entire body with innerHTML
.
You can use insertAdjacentHTML
to insert an HTML string:
document.body.insertAdjacentHTML('afterbegin', htmlStr);
Or you can prepend some element:
var el = document.createElement('div');
// ... insert your data to `el`document.body.insertBefore(el, document.body.firstChild);
Solution 4:
W3Scools says:
Definition and Usage The write() method writes HTML expressions or JavaScript code to a document.
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.
Note: When this method is not used for testing, it is often used to write some text to an output stream opened by the document.open() method. See "More Examples" below.
Post a Comment for "Is There A Way To Use Document.write But Write To The Top Of The Body?"