简体   繁体   中英

Add tags to <head> reliably in Javascript

I am writing a program that does the following:

  • Creates an iframe in the DOM
  • Makes an AJAX request to a page (a site's main page)
  • If the page has changed, I use iframe.srcdoc = contents; to the iframe, where contents is what came back from AJAX

Note that this way any image etc. with a relative URL specified will not render correctly. To make it look right, I have to add a <base> tag to <head> .

I am very reluctant to use regexp like this:

contents = contents.replace('<head>','<head><base href="http://www.example.com/">');

Because it might stuff things up (but, am I being way too overcautious and over-paranoid?).

NOTE : I cannot do this by manipulating DOM: if I do iframe.srcdoc = contents; and then add the <base> tag, the page will still render incorrectly. The <base> tag needs to be there before I assign it to iframe.srcdoc ...

How would you go about this?

Merc.

使用appendChild DOM操作添加元素。

document.getElementsByTagName('head')[0].appendChild('<base href="http://www.site.com" />');

In my holy opinion using appendChild with string-values it not the best idea, so here is my approach.

// create new "base"-node
var node = document.createElement('base');
// set href="http://www.site.com"
node.setAttribute('href', 'http://www.site.com');
// append new "base"-node to first "head"-node in html-document
document.getElementsByTagName('head')[0].appendChild(node);

see W3-School The HTML DOM (Document Object Model) for details about DOM-Manipulation, DOM-Understanding and Javascript-Reference.

Solution for inject "base"-tag with string-manipuation (kind of "non-dom-offline") is Regex to prepend base-tag before closing head-tag.

contents = contents.replace(/<\/head>/ig, '<base href="http://www.site.com" />$&');

An other solution can is using jQuery to construct an "offline-DOM" of the contents of the iframe and using DOM-Manipulation-Methods.

contents = jQuery(contents).find('head:first').append('<base ... />').html()
// no guarantee here that this will work ;-) it was just out of my mind, but should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM