4

I have a html page with no doctype declared deployed to a server(say A). This is fetching js files from another server(say B). js creates necessary html page to display. Now IE8 is creating problems as there is not doctype declared(sets itself to IE5 quirks mode)

Now doctype is the first line read, and this seems impossible to be done this way(using js to set the doctype). Is it possible to set a meta tag instead to set the page to standards mode? Or is there any other i can set the page to standard page without modifying the html page from server A.

bhb
  • 2,288
  • 2
  • 15
  • 31
  • 2
    http://stackoverflow.com/questions/tagged/x-ua-compatible - however if you can set a meta tag you can set the doctype. Both have to be read at load time - also read this http://stackoverflow.com/questions/2518256/override-intranet-compatibility-mode-ie8 – mplungjan Feb 03 '14 at 09:22
  • possible duplicate http://stackoverflow.com/questions/3509798/how-can-we-add-a-doctype-using-javascript – Michal Brašna Feb 03 '14 at 09:34

1 Answers1

5
var nodeDoctype = document.implementation.createDocumentType(
 'html',
 '-//W3C//DTD XHTML 1.0 Transitional//EN',
 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtdd'
);
if(document.doctype) {
    document.replaceChild(nodeDoctype, document.doctype);
} else {
    document.insertBefore(nodeDoctype, document.childNodes[0]);
}

Update based on your comment:

It is possible to change the doctype with JS to enable compatability viewing (as done here: http://www.webmasterworld.com/forum91/4856.htm) but is quite a nasty hack and not recommended. Ideally you can do this server side. So have a doctype js parameter and then do a page reload:

window.location = window.location+"?doctype=newdoctype"

This will cause the page to reload which might not suit you, but is the safest way to do it.

BMiner
  • 14,934
  • 11
  • 47
  • 52
S..
  • 4,821
  • 1
  • 32
  • 39
  • 2
    will the browser reread the doctype. the html page is already loaded. – bhb Feb 03 '14 at 09:43
  • btw `document.doctype is null` – bhb Feb 03 '14 at 09:45
  • how do i do this in IE. `createDocumentType` is not avaialable in – bhb Feb 03 '14 at 12:45
  • Interesting. I was tempted to say this answer is completely wrong since the DOCTYPE is actuall used by the XML parser to determine how to interpret and validate the (X)HTML/XML markup, thus it's useless to modify an already parsed DOM to change the doctype. But it's IE and might really work. "`A Document Type Definition (DTD) defines the legal building blocks of an XML document. It defines the document structure with a list of legal elements and attributes.`" [Wikipedia: DOCTYPE](http://en.wikipedia.org/wiki/Document_type_definition) – try-catch-finally Jan 06 '15 at 20:02
  • 1
    The browser will not reread the doctype if you add it with javascript – deKajoo Feb 16 '18 at 15:21