Add HTML string to head-section of page [duplicate] - javascript

I'm working with a CMS, which prevents editing HTML source for <head> element.
For example I want to add the following above the <title> tag:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />

You can select it and add to it as normal:
$('head').append('<link />');

JavaScript:
document.getElementsByTagName('head')[0].appendChild( ... );
Make DOM element like so:
const link = document.createElement('link');
link.href = 'href';
link.rel = 'rel';
document.getElementsByTagName('head')[0].appendChild(link);

jQuery
$('head').append( ... );
JavaScript:
document.getElementsByTagName('head')[0].appendChild( ... );

You can use innerHTML to just concat the extra field string;
document.head.innerHTML = document.head.innerHTML + '<link rel="stylesheet>...'
However, you can't guarantee that the extra things you add to the head will be recognised by the browser after the first load, and it's possible you will get a FOUC (flash of unstyled content) as the extra stylesheets are loaded.
I haven't looked at the API in years, but you could also use document.write, which is what was designed for this sort of action. However, this would require you to block the page from rendering until your initial AJAX request has completed.

In the latest browsers (IE9+) you can also use document.head:
Example:
var favicon = document.createElement('link');
favicon.id = 'myFavicon';
favicon.rel = 'shortcut icon';
favicon.href = 'http://www.test.com/my-favicon.ico';
document.head.appendChild(favicon);

Create a temporary element (e. g. DIV), assign your HTML code to its innerHTML property, and then append its child nodes to the HEAD element one by one. For example, like this:
var temp = document.createElement('div');
temp.innerHTML = '<link rel="stylesheet" href="example.css" />'
+ '<script src="foobar.js"><\/script> ';
var head = document.head;
while (temp.firstChild) {
head.appendChild(temp.firstChild);
}
Compared with rewriting entire HEAD contents via its innerHTML, this wouldn’t affect existing child elements of the HEAD element in any way.
Note that scripts inserted this way are apparently not executed automatically, while styles are applied successfully. So if you need scripts to be executed, you should load JS files using Ajax and then execute their contents using eval().

Try a javascript pure:
Library JS:
appendHtml = function(element, html) {
var div = document.createElement('div');
div.innerHTML = html;
while (div.children.length > 0) {
element.appendChild(div.children[0]);
}
}
Type:
appendHtml(document.head, '<link rel="stylesheet" type="text/css" href="http://example.com/example.css"/>');
or jQuery:
$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', 'http://example.com/example.css'));

With jquery you have other option:
$('head').html($('head').html() + '...');
anyway it is working. JavaScript option others said, thats correct too.

Related

Use JS variable to set the src attribute for <script> tag

I want to use a javascript variable as a 'src' attribute for another tag on the same jsp.
<script>
var link = mylink // the link is generated based on some code
</script>
I want to create this new element as shown below.
<script src="mylink">
</script>
On searching various forums, I have tried using the following options but they don't seem to work. I want this thing to work on all major browsers.
Put this code in the first element.
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "path/to/somelink";
document.body.appendChild(script);
Use document write method in the first element.
document.write("<script type='text/javascript' src="+ google.com + "><\/script>");
Tried to set a JSTL Variable in the first element and use it.
<c:set var="URL" value="mylink"/>
None of these ways were successful. Any suggestions on what is going wrong?
Though CDATA works fine, using document.createElement is also a great choice.. Especially if you intend to append some value to a URL, say for cache busting..
<script type="text/javascript">
var JSLink = "/Folder/sub_folder/version.js?version=" + Math.random();
var JSElement = document.createElement('script');
JSElement.src = JSLink;
JSElement.onload = OnceLoaded;
document.getElementsByTagName('head')[0].appendChild(JSElement);
function OnceLoaded() {
// Once loaded.. load other JS or CSS or call objects of version.js
}
</script>
Code well.. :)
I use something similar to choice two. There is a slight mistake in your code because "google.com" needs to be surrounded by quotes.
To improve compatibility, you might want to write it as:
document.write("<script type='text/javascript' src='"+ x + "'><\/scr" + "ipt>");
In this situation, x would be the file to be included. You can define it as:
var x = "http://google.com/script.js";
OR
var x = "path/to/script.js";
Are you able to use jQuery? If so you could use getScript():
http://api.jquery.com/jQuery.getScript/
$.getScript(mylink, function() {
// do something using the JS that was loaded.
});
Try:
(function(d){
var file = 'yourJS.js';
var ref = d.getElementsByTagName('script')[0];
var js = d.createElement('script');
js.src = file;
ref.parentNode.insertBefore(js, ref);
}(document));
What this does:
Find the first script element on your page
Creates a new script element with your supplied source.
Then inserts that new element before the first existing script element.
<xsl:variable name="Path" select="/root/folder/"></xsl:variable> <!-- Global path variable. -->
<xsl:variable name="myScriptPath" select="concat($Path, 'myScript.js')"></xsl:variable> <!-- Relative script path variable. -->
<script src="{$myScriptPath}"/> <!-- Attach script. -->

Print in the background with javascript i.e. without document pop up

Found this code to print from javascript. But it opens a window with the document to be printed. Is there a way to hide that document?
var element=document.getElementById(element_id);
var newWin=window.open('','Print-Window','width=400,height=400,top=100,left=100');
newWin.document.open();
/* newWin.document.title = "Readings on PageLinks"; */
newWin.document.write('<html><head><title>Readings on PageLinks</title></head><body onload="window.print()">'+element.innerHTML+'</body></html>');
newWin.document.close();
setTimeout(function(){ newWin.close(); },10);
The print is done onload() for that document, so I guess printing could not be done without it. But can it be hidden?
You can accomplish this using a print-specific stylesheet as described in How to print only a selected HTML element? Don't use window.open() at all; use CSS classes (dynamically applied if need be) to specify which elements should/shouldn't be printed.
Add this to your markup:
<iframe id="ifrOutput" style="display:none;"></iframe>
Add the following javascript function:
function printContainer(content, styleSheet) {
var output = document.getElementById("ifrOutput").contentWindow;
output.document.open();
if (styleSheet !== undefined) {
output.document.write('<link href="' + styleSheet + '" rel="stylesheet" type="text/css" />');
}
output.document.write(content);
output.document.close();
output.focus();
output.print();
}
And call it like so:
// with stylesheet
printHtml('<div>Styled markup</div>', 'printStyles.css');
// without stylesheet
printHtml('<div>Unstyled markup</div>');

javascript nullifies when setting the document.body.innerHTML

Good day.
I am currently working on a project that prints a desired <div> to a printer.
Here is the code:
var printContents = document.getElementById(id).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
document.body.style.display = "none";
window.print();
document.body.innerHTML = originalContents;
document.body.style.display = "block";
This code works and prints the desired <div>, but after that I need to put back the previous page again so I used this statement:
document.body.innerHTML = originalContents;
document.body.style.display = "block";
This displays the previous page but the functionalities of my buttons are gone?! Can someone explain to me what happened and is there a solution to this problem? Thanks in advance!
This is happening because you've wiped out the old DOM which had events wired up to it, and replaced it with a totally new, different DOM that just happens to have the same HTML.
Presumably you're taking this approach because the printable zone is determined at runtime. A less-destructive solution might be to create a new <iframe> and copy the desired markup into that; then invoke print() on the iframe. Something like:
var printElement = function(element) {
var frame = document.createElement('iframe');
document.appendChild(frame);
frame.contentDocument.innerHTML = element.innerHTML;
frame.contentWindow.print();
document.removeChild(frame);
};
You'll also need to copy over any CSS references into the <iframe>.
(note this is pseudo-code and not tested)
Your code clears the document and then puts back the HTML stored in originalContents, but this variable stores only a string, so all previously registered event handlers are gone.
Why don't you create a print stylesheet and hide everything except the content that you want to print?
<link rel="stylesheet" type="text/css" href="print.css" media="print">
When you reset the innerHTML, you don't get all your event handlers back. They are wiped out when you create entirely new DOM elements.
One idea would be to have two master divs in the body, one that is your normal display and one that is what you want to print. You can then hide whichever one you don't want to display like this:
<body>
<div id="mainContent">main screen content goes here</div>
<div id="printContent">generated print content goes here</div>
</body>
// hide main content
var mainDiv = document.getElementById("mainContent");
mainDiv.style.display = "none";
// put content to print in the print div and show it
var printDiv = document.getElementById("printContent");
printDiv.innerHTML = document.getElementById(id).innerHTML;
printDiv.style.display = "block";
// print
window.print();
// restore visibility
mainDiv.style.display = "block";
printDiv.style.display = "none;
You could also just use the whole body for printing and use a stylesheet with media="print" to control the visibility of the things you do/don't want to print.
You can add a click event to all dives inside your page so that user can click the div.
after that add a class to that div which the class is defined within the print CSS file.
inside css print file use the following code:
`*{display:none}
.printableDiv{display:block}`
to define a print css file use this code :
<link rel="stylesheet" type="text/css" href="print.css" media="print"> (which Rafael has told you ).
good luck

CSS style refresh in IE after dynamic removal of style link

I've got a problem with the dynamic style manipulation in IE7 (IE8 is fine). Using javascript I need to add and remove the < link /> node with the definition of css file.
Adding and removing the node as a child of < head /> works fine under Firefox. Unfortunately, after removing it in the IE, although The tag is removed properly, the page style does not refresh.
In the example below a simple css (makes background green) is appended and removed. After the removal in FF the background turns default, but in IE stays green.
index.html
<html>
<head>
</head>
<script language="javascript" type="text/javascript">
var node;
function append(){
var headID = document.getElementsByTagName("head")[0];
node = document.createElement('link');
node.type = 'text/css';
node.rel = 'stylesheet';
node.href = "s.css";
node.media = 'screen';
headID.appendChild(node);
}
function remove(){
var headID = document.getElementsByTagName("head")[0];
headID.removeChild(node);
}
</script>
<body>
<div onClick="append();">
add
</div>
<div onClick="remove();">
remove
</div>
</body>
</html>
And the style sheet:
s.css
body { background-color:#00CC33 }
Here is the live example: http://rlab.pl/dynamic-style/
Is there a way to get it working?
Rybz, I, personally, would setup an "initial" style sheet to reset back to (also because it helps reset browsers to "my" desired initial settings, not the browser defaults) and when removing the style sheet from the DOM I would insert the one to reset to. I don't know if this will work for what you are trying to do, but it worked for me in the similar situation, and if I remember correctly I was having the same problem as you do, and that fixed it.

getting the HEAD element from overlay.js firefox plugin

I have a lightwiehgt plugin to firefox which needs to inject a script into the HTML.
The code looks like this:
var head = document.getElementsByTagName("head")[0];
var newscrpt;
newscrpt = document.createElement('script');
newscrpt.type = "text/javascript" ;
newscrpt.src = "http://blabla.com/...";
newscrpt = head.appendChild(newscrpt);
The problem is that document.getElementsByTagName("head")[0] returns 'undefined', and checking document.getElementsByTagName("head").length is 0.
It currently executes on the browser document.onLoad event but I also tried calling it from window.setTimeout to make sure it is not a problem with loading synchronization, but the same happens.
Any ideas from anyone?
Thanks!
If you're using a frame or an iframe object, you should not reference the document directly but do something like:
var doc = frame.contentWindow.document;
After that you can get the head. I'm using jQuery to add some resources to it:
$(doc).find('head').append(
'<link type="text/css" rel="stylesheet" href="MyStylesheet.css" />');
Hope it helps.

Categories

Resources