2

I need to insert new tags in html head. Not in document, in string that contains html. So regular expression is only way.

<head>
<title>Html</title>
</head>

And get something like this:

<head>
<title>Html</title>
<script src="some_path.js"></script>
</head>

And more:

<head>
<title>Html</title>
<script src="some_path.js"></script>
<script src="some_path_2.js"></script>
</head>
5
  • <head> is a tag just like any other in page...no need for regex. You can append to it Commented Nov 4, 2013 at 14:29
  • Since this is not DOM parsing but string parsing, how about avoiding the regexes, and parse out the string instead? A simple tokenizer would do wonders. Commented Nov 4, 2013 at 14:29
  • What is your context where you have no access to the DOM? Commented Nov 4, 2013 at 14:54
  • The best solution so far. var wholeHtml = "<head><meta charset='utf-8'></head>"; wholeHtml.replace(/(<head.*\><meta.*>)(<\/head>)/g, '$1<script src="some_path.js"><\/script>$2'); Commented Nov 4, 2013 at 15:12
  • @AntonAleksandrovichTrofimenk - That's really not the best solution, it relies on there being a meta tag immediately after some other tag and it's replacing a whole backreference that is completely unnecessary. I would take a look at Michael's solution Commented Nov 4, 2013 at 15:19

5 Answers 5

2

Use this:

function injectScript (id, src, async) {
    var js,
    fjs = document.getElementsByTagName("head")[0];

    if (document.getElementById(id))
        return;

    js = document.createElement("script");
    js.id = id;
    js.src = src;
    js.type = 'text/javascript';

    if (async) {
        js.async = true;
    }

    fjs.appendChild(js, fjs);
}

Will prevent double injection and support asynchronous scripts.

Sign up to request clarification or add additional context in comments.

Comments

1

This is possible. Just get the <head> element and add children to it as usual:

document.getElementsByTagName("head")[0].appendChild(whatever);

For more information on how this works you can google for "Javascript DOM".

1 Comment

per the OP "Not in document [DOM], in string that contains html."
1

If you only have the HTML available as a string, and not as a DOM-document, you can do simple insertions prior to the head-close tag without resorting to regexes. The following code makes use of the splice method in this answer. It could be made a function instead of a prototype, and have the second parameter removed for our purposes:

String.prototype.splice = function( idx, rem, s ) {
    return (this.slice(0,idx) + s + this.slice(idx + Math.abs(rem)));
};

var insertTag = function(newTag, html) {
  var end = html.indexOf('</head>');
  return html.splice(end, 0, newTag);
}

So if you had

var doc = '<head><title>Html</title></head>';

and you ran

var doc = insertTag('<script src="some_path.js"></script>', doc);

You would get

<head><title>Html</title><script src="some_path.js"></script></head>

The function is simple, and doesn't check for existence of the head-close tag, or any other safety concerns that might need to be taken. It would would with line-breaks, and is just given as a general idea of how to avoid DOM (per question) and regexes (per saving your sanity).

However, if you have a DOM available -- use it.

2 Comments

Given the very limited scope of the question and the (horrible) requirement to not use DOM, this is probably the simplest possible approach.
I might even use the the term "dumb" instead of simple. But it does work. For certain limited definitions of term "work."
0
(function(){
  var newscript = document.createElement('script');
     newscript.type = 'text/javascript';
     newscript.async = true;
     newscript.src = 'some_path.js';
  (document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(newscript);
})();

Comments

0

If you want to get the name of the page into the title head, you can use window.onload before the title tag and it will search the selector to insert into .

In this example we are searching the page for an H3 tag. (Could be h2, h1...)

<!doctype html>
<html lang="en">
<head>
[other metas]
<script>window.onload = function(){
var h3Text = document.querySelector("h3").innerText;
return document.querySelector("title").innerHTML = h3Text;
}</script>
<title></title>
</head><body><h3>This Will Go Into the Title Tag</h3>....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.