Neta Meta
Neta Meta

Reputation: 4047

javascript prepending to head?

I am trying to use jquery UI for slider in a bookmarklet. and jquery ui requires to include the file after normal jquery file.

So what I've tried so far was just appending the script to header while making sure that ui get added after normal jquery but this did not work i suspect it might be because i appended it and not pre pended it.

So i am now looking for ways to pre pend in Javascript after some time searching i've found :

var parent_head = document.getElementsByTagName("head")[0];

document.getElementsByTagName("head")[0].appendChild(jqueryUI, parent_head.firstChild);

This however seems to append it in a normal way.

Is there a better way?

Upvotes: 0

Views: 3240

Answers (1)

Mike Samuel
Mike Samuel

Reputation: 120496

Use insertBefore with the first child as the insertion point.

parent_head.insertBefore(jqueryUI, parent_head.firstChild)

For example,

var list = document.createElement('ul');
document.body.appendChild(list);
list.innerHTML = "<li>First</li><li>Second</li>";

var newItem = document.createElement('li');
newItem.innerHTML = "Firster";

list.insertBefore(newItem, list.firstChild);

shows

  • Firster
  • First
  • Second

Upvotes: 3

Related Questions