Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add anything in <head> through jquery/javascript?

People also ask

How do you append something in jQuery?

jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.

Can JavaScript be added in head only?

No, it can be anywhere.

What is $$ in jQuery?

$ sign is just a valid javascript identifier which is used as an alias for jQuery. Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function). Most of them also have a way to relinquish the $ so that it can be used with another library that uses it.


You can select it and add to it as normal:

$('head').append('<link />');

JavaScript:

document.getElementsByTagName('head')[0].appendChild( ... );

Make DOM element like so:

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);