Javascript: document.write to add external content? - javascript

Page a.com loads a javascript file from b.com like this:
<script src="http://b.com/file.js"></script>
b.com/file.js adds some content to a.com.
The file.js is like this:
document.write("<script ... <link rel=\"stylesheet\" ... <div> ... <form> ...");
But I know document.write is not good. But what are the alternatives? I don't think it's "ok" to add complete html code inside document.write ... or not?

There is nothing "not good" about using document.write here, especially when you want to add in some <script> to the page. If you are just using it to add DOM elements, you can consider using some DOM manipulation methods.

Related

Javascript can't find the script tag's id

I am facing problem with javascript document.getElementByID function. The HTML file is:
...
<script
id="scriptID"
type="text/javascript"
src="http://external.script.com/file.js">
</script>
...
When the page is loaded, the script is successfully included, but when executing expression from that file (the script is executed automaticaly after loading it):
... = document.getElementById('scriptID').src
The script fails with message saying that "document.getElementById('scriptID') is null".
Can anybody tell me, why it is null if the tag is the script tag itself?
Thx for any response.
EDIT:
I don't know if that is relevant, but the page is built in a bit more complicated way.
There is page of some product. When the customer orders that product, there is a div loaded by AJAX with some "Thanks for order" and that contains the script. Then the script is executed.
May be your DOM is not ready when you are try to get src of script,
<script id="scriptID" type="text/javascript" src="http://external.script.com/file.js">
</script>
window.onload=function()
{
alert( document.getElementById('scriptID').src);
}
Its workinfg fine SEE

loading html code with html

I want javascript to load a html code so it can be embedded in a page, all I get is the raw html code without being compiled.
<script>
document.write('http://www.example.com/index.php?title=Media:Object4&action=raw&ctype=html')
</script>
It contains the html coding inside and I want it to embed in pages so I can share with other websites.
Are you trying to get the HTML from that URL and embed it in the page? JavaScript can't do that for security reasons, but if you're using PHP server-side you can use:
echo file_get_contents("http://..........");
Or you can use an iframe:
<iframe src="http://........" />
The easiest way to make this work, sort of, is by using <iframe>:
<iframe src="http://www.example.com/index.php?title=Media:Object4&action=raw&ctype=html"></iframe>
If you want to load it inside a particular container, you have to perform a web request using JavaScript; jQuery example:
<div id="container"></div>
<script>
$('#container').load('http://www.example.com/index.php?title=Media:Object4&action=raw&ctype=html');
</script>
If the remote URL is not in the same domain, you need to use a proxy:
<script>
$('#container').load('/path/to/myproxy.php', {
url: 'http://www.example.com/index.php?title=Media:Object4&action=raw&ctype=html'
});
</script>
Then your PHP code could look like:
<?php
if (parse_url($_POST['url'], PHP_URL_HOST) === 'www.example.com') {
echo file_get_contents($_POST['url']);
}
document.write - adds text to the document - it does not fetch documents from the web.
However, you can use the object tag.
It should look something like that:
<object type="text/html" data="http://www.example.com/index.php?title=Media:Object4&action=raw&ctype=html" style="width:100%; height:100%"></object>
Additionally, if the page that you are fetching is on the same domain, you can use AJAX to fetch it.

Embedding XML in HTML

How would one go about embedding XML in a HTML page?
I was thinking using CDDATA would be the best approach but I get errors in the HTML document when the page loads.
<script><![CDATA[ ... ]]></script>
I'm needing to embed a XML document for fetching later with JavaScript. I need to do this since when the user opens it, they might not have internet access.
As long as the XML doesn't contain </script> anywhere, you can put it inside the script tags with a custom type attribute (and no CDATA section). Give the script tag an id attribute so you can fetch the content.
<script id="myxml" type="text/xmldata">
<x>
<y z="foo">
</y>
</x>
</script>​
...
<script> alert(document.getElementById('myxml').innerHTML);​ </script>
http://jsfiddle.net/hJuPs/
How about:
<script>
var xml = '<element> \
<childElement attr="value" /> \
</element>';
</script>
That would enable you to easily embed the XML for later retrieval in javascript.
According to the tutorial here, you can use the 'xml' tag to embed XML data within an HTML document. However, this implicitly displays the XML data in the browser.
http://www.expertrating.com/courseware/XMLCourse/XML-Embedding-HTML-8.asp

Meteor.js: <script> tag doesn't work inside <body>

A simple script tag inside the body tag doesn't seem to work. The alert doesn't get triggered in the code below:
<body>
<script type="text/javascript">
alert('Hello');
</script>
{{>main}}
</body>
Any idea why?
Edit:
Just tried it with a fresh meteor app, no alert tag still:
<head>
<title>test</title>
</head>
<body>
<script type="text/javascript">
alert('Hello');
</script>
{{> hello}}
</body>
<template name="hello">
<h1>Hello World!</h1>
{{greeting}}
<input type="button" value="Click" />
</template>
Weird thing is when I copy paste the source of the html, made a new html page, and the alert will work.
Edit3: I deployed this app here: http://alert-in-body-test.meteor.com/
Do you get an alert box?
This question is still relevant in the current version of Meteor (version 0.5.4) so I wanted to describe how to include script at the end of the body.
To execute javascript at the end of the body, register a Handlebars helper and put the relevant code there, like this:
In client.html:
<body>
{{renderPage}}
{{afterBody}}
</body>
...
In client.js:
if (typeof Handlebars !== 'undefined') {
Handlebars.registerHelper('afterBody', function(name, options) {
$('body').append('AFTER BODY');
});
}
(For a great description of why this is required, see Rahul's answer to a similar question here: https://stackoverflow.com/a/14002991/219238 )
Its working for me
in onrender call this jquery
$.getScript('yours url')
It should work.
I have just pasted this inside one of my projects and it worked.
Your {{>main}} is strange for me tough. Also make sure that <body> is inside <html> tag.
Meteor is constructing the entire DOM from Javascript by rendering your page as a template -- the 'source' for your page as seen by the browser is basically:
<script type="text/javascript" src="/5a8a37bef5095c69bcd3844caf3532e1ba6d49bf.js"></script>
I can't find a definitive page stating that embedding a script tag in a template like this won't cause it to be executed, but it definitely feels against the spirit of what the framework is trying to achieve.
If the point is to achieve a clean separation of your markup and logic then why put it in the template. A better solution would be to use the meteor.startup call
Instead of looking the rendered html at developer tools, try looking the real downloaded html.
You will find a (probably) empty tag, with tons of script tags inside the .
In other words, the body of your meteor application is not the body of the final html, it's just your main template.
Instead, this ton on scripts shipped by Meteor, will load your templates.
So, your code will not run, cause it's been placed there. It's like when you manipulate DOM (with jQuery, for exemple), placing a script tag in DOM, after it's loaded. This script tag will not run.

Can you make a javascript function replace itself on the page with custom html?

I have some javascript which will create some sort of widget on a page. I will be giving this snippet to clients so I want them to have to do very little.
The most obvious solution which I have work right now looks something like this:
<div id="divContent"></div>
<script type="text/javascript">
MakeWidget('divContent');
</script>
Make widget basically looks for the divContent div and fill it with my widget's html.
Is there a better way to do this?
Can you replace a Script Tag with a Div using Javascript in that Script Tag?
I would really like it if I could reduce the code down to only the MakeWidget function and it would replace itself and the script tag with the html the function generates.
Edit - I essentially want to generate HTML exactly where the MakeWidget function is called on the page.
Can you replace a Script Tag with a Div using Javascript in that Script Tag?
Yes. When the <script> element is reached, assuming it is not a defer or async script, it will be the last script element in the page so far. So you can say, either inline or in an external script:
<script type="text/javascript">
(function() {
var scripts= document.getElementsByTagName('script');
var script= scripts[scripts.length-1];
var div= document.createElement('div');
div.innerHTML= 'Whatever content is going to be inserted';
script.parentNode.insertBefore(div, script);
})();
</script>
You have to have MakeWidget defined somewhere, right? Presumably this is going to be in an external script. Why not just have the external script source just attach itself to the divContent using the window.onload method?
This would result in this code on your client's page:
<script src="http://foo.com/makewidget.js"></script>
Your makewidget.js code could then look like this:
window.onload = function() { MakeWidget('divContent') }
There may some issues with other scripts loading and probably some cross-browser compatibility issues but that should get you pointed in the right direction.
So you want to have a script element which replaces itself with div.
Your initial code is like this:
<div id="divContent"></div>
<script>
MakeWidget('divContent');
</script>
You can rewrite it like this (I am using JQuery):
<script id="scriptContent">
$('#scriptContent').after('<div id="divContent"></div>');
MakeWidget('divContent');
$('#scriptContent').remove();
</script>
I have not tried it though!
I would think it would be possible to do it as follows:
<div id="divWidgets">
<script type="text/javascript">
MakeWidgets("divWidgets");
</script>
</div>
The end result should be (if I understand your description correctly) that MakeWidgets will replace the contents of the DIV, which, in this case, is the script itself.

Categories

Resources