简体   繁体   中英

How to embed HTML via JS embed code

I need to give the user a snippet of js code that will insert some HTML code into the page.

I'm wondering what the best method to do so is. Should I use document.write, should I just create all the HTML elements via DOM programmatically?

Is it possible to use a js library? I can see conflicts occurring if the webpage the code is embedded in already contains the library.

Using a library is probably too heavyweight, inserting DOM elements is very verbose and document.write may not work if the target site uses the application/xhtml+xml content type. I think your best bet is to construct one element using document.createElement and then setting innerHTML on that.

A suggestion:

Insert this DIV wherever you want the output to appear:

<div id="uniqueTargetID" style="display: none;"></div>

Then at bottom of page have this:

<script src="snippet.js"></script>

This file (remotely hosted or otherwise) contains could output simple text this way:

var html = [];
html.push('<h1>This is a title</h1>');
html.push('<p>So then she said, thats not a monkey, its a truck!</p>');
html.push('<p>You shoulda seen his face...</p>');
var target = document.getElementById('uniqueTargetID');
target.innerHTML = html.join('');
target.style.display = 'block';

I would avoid using document.write() if you can help it.

Javascript::

//to avoid global bashing
(function(){
  var target = document.getElementById('ScriptName'),
    parent = target.parentElement,
    oput = document.createElement('div');
  oput.innerHTML = "<p>Some Content</p>";
  parent.insertBefore(oput, target);
}());

HTML to give to client/people::

<script type="text/javascript" id="ScriptName" src="/path/to/ScriptName.js"><script>

ScriptName should be something unique to your script.

If its simple insertion you can use pure js, otherwise if you want to provide some complex functionality you can use library. The best choice in this case will be the lib that does not extend root objects (Array, Function, String) to prevent conflicts (jQuery in noConflict mode, YUI, etc.).

Anyway it will be better to avoid using document.write u'd better use setting of innerHTML of existing element or create new one.

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