Load script after inserting it to an element - javascript

We have page like this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="abc"></div>
</body>
</html>
I want to insert script in div and run it.
So im doing something like this:
document.getElementById("abc").innerHTML="<script>alert('sup');</script>";
Good, script is inside that div, but how can i run it now?
I propably didn't make it clear:
I have an external script that i need to put in specified place on the page.
I don't have access to the website, so i can't put it on the page code.
I want to do this, becouse this script makes new objects on the place where it is putted.
I don't have access to that script. I just have link (not direct) to it.

Make it a function. Use <script>function myAlert(){alert('sup');}</script> instead. You can then call it with myAlert();.

Please use createElement for that
var div = document.getElementById('abc');
var script = document.createElement('script');
var code = document.createTextNode('alert("sup");');
script.appendChild(code);
div.appendChild(script);
To put a script in a div is only useful for document.write And please don't do that. :-)

Related

HTML/javascript: prevent paint before code executes

I have a page with a javascript file at the end. the file is placed at the end so that I get access to all the dom elements.
let us say the markup looks like this
<html>
<head></head>
<body>
//lot of markup here
<script src="my-js.js"></script>
<body>
the sample markup is just to show the location of my js file.
the first like in the js file (my-js.js) is
document.body.style.visibility = 'hidden';
After the code runs I set the visibility back to hidden
From what I have understood(from a lot of articles related to this including in stackoverflow ones) is that the browser reaches the js, then executes it, and then continues with render and then paints.
If that was true, my code as described should work fine.
However, what is happening now is that, the page is shown (for less than 500ms) as it is before the code executed, then quickly hidden and then shown again after the code executed.
in short, what I want is:
page is hidden > code executes > page is shown
instead what I get is
page is shown > page is hidden > code executes > page is shown
My question is why is the page shown for that split second? what am I doing wrong here?
PS: Please note that I cannot change the location of the js nor add another. So, do not post any solution that suggest the same.
More importantly, I want to know why my code is wrong.
You might be interested in using the defer method.
defer means “wait for the parser to finish to execute this”. It’s roughly equivalent to binding your script to the DOMContentLoaded event, or using jQuery.ready. When the code does run, everything in the DOM will be available for you to use. Unlike async, defer’d code will run in the order it appears in the HTML of the page, it is just deferred until after the HTML is fully parsed.
For example:
<script src="my-js.js" defer></script>
See more here
Put the script tag right at the start of the body so it will be evaluated almost exactly as the body is rendered.
<html>
<head></head>
<body>
<script>
document.body.style.visibility = 'hidden';
</script>
<p>Sample text</p>
</body>
</html>
You can also add a style tag to set the body's visibility to hidden.
body{
visibility: hidden;
}
<html>
<head></head>
<body>
<p>Sample text</p>
</body>
</html>

extract load in div

i use this script that uses the load function and inserts it in a div
<div id="NomeUtente"></div>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$("#NomeUtente").load('http://www.ilfree.it/index.php?/nome.html/');
</script>
it is possible through php to draw in content within the div?
I wish I could pick up the result in the div and then use it on php... help me please
Unsure about what you mean by a php page. But you can read the contents of a div using jquery's html function.
var htmlContent = $("#NomeUtente").html();

change innerHTML to nearby document

I would like to have a section of my webpage's contents to change upon a button click. However, the content I'd like to have change includes formatting itself, and I would prefer to have the content in a separate document.
I would like it to look something like this, but I'm okay with any solution:
<html>
<head>
<script type="text/javascript">
function swap() {
document.getElementById('toChange').innerHTML = '<!--#include virtual="../newContent.htm"-->';
}
</script>
</head>
<body>
<span id="toChange">Temp Text</span>
<input type="button" onclick="swap()" value="Change" />
</body>
</html>
The problem is obviously with the include statement in swap() but I don't know how to change it appropriately. Thanks.
Basically server side includes don't work in this context; you will have to resort to AJAX requests.
You didn't tag your question with jquery, but you could read up what it does behind the scenes:
function swap() {
$('#toChange').load('../newContent.htm');
}
jQuery.load() reads the contents from ../newContent.htm using an AJAX call and then stores that HTML inside the toChange span.
As far as I know your probably going to need JSON and AJAX for your request. I do know that changing the data content without making a new request is what JSON and AJAX are used for mostly. It will update the page dynamically without reloading. JSON is built-in to Javascript so your actually on the right path. Hopefully it helps somewhat.

How to replace Current script tag with HTML contents generated by the same script

I want to replace the current script tag with the HTML contents generated by the same script.
That is, my Page is
<html>
<body>
<div>
<script src="myfile1.js"></script>
</div>
<div>
<script src="myfile1.js"></script>
</div>
</body>
</html>
Inside each .js file corresponding html contents are generated. I want to put the contents as the innerHTML of the parent div. But can't set id for the parent div because the page is not static. So the current script tag must be replaced with the HTML content. How can I do this?
For each script tag src is the same. So can't identify with src. These scripts displays
some images with text randomly. Scripts are the same but displays different contents in divs on loading
Please help me
try inside of myfile1.js:
var scripts = document.getElementsByTagName( "script" );
for ( var i = 0; i < scripts.length; ++ i )
{
if ( scripts[i].src == "myfile1.js" )
{
scripts[i].parentNode.innerHTML = "new content";
}
}
This is a great question for those trying to implement a JSONP widget. The objective is to give the user the shortest possible amount of code.
The user prefers:
<script type="text/javscript" src="widget.js"></script>
Over:
<script type="text/javscript" src="widget.js"></script>
<div id="widget"></div>
Here's an example of how to achieve the first snippet:
TOP OF DOCUMENT<br />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
// inside of widget.js
document.write('<div id="widget"></div>');
$(document).ready(function() {
$.getJSON('http://test.com?remote_call=1', function(data) {
$('#widget').html(data);
});
});
<br />BOTTOM OF DOCUMENT
Have a look at: http://alexmarandon.com/articles/web_widget_jquery/ for the correct way to include a library inside of a script.
document.currentScript has been available since 2011 on Firefox and 2013 on Chrome.
document.currentScript documentation at MDN
<!DOCTYPE html>
<meta charset="UTF-8">
<title>currentScript test</title>
<h1>Test Begin</h1>
<script>
document.currentScript.outerHTML = "blah blah";
</script>
<h1>Test End</h1>
Unfortunately a running JavaScript file is not aware of where it is running. If you use document.write() in the script, the write function will take place wherever the script runs, which would be one way to accomplish what you want, but without replacing the contents or being able to perform any actions on the enclosing DIV.
I can't really envisage a situation where you'd have such stringent restrictions on building a page - surely if the page is dynamic you could generate identifiers for your DIV elements, or load content in a more traditional manner?
Why not use Smarty?
http://www.smarty.net/
You can use javascript in Smarty templates, or just use built-in functions.
Just take a look at http://www.smarty.net/crash_course
poof -- old answer gone.
Based on your last edit, here's what you want to do:
<html>
<head>
<!-- I recommend getting this from Google Ajax Libraries
You don't need this, but it makes my answer way shorter -->
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function getRandomContent(){
// I expect this is the contents of your current script file.
// just package it into a function.
var rnd = Math.random();
return "[SomeHtml]";
}
$('.random').each(idx, el){
$(this).html(getRandomHtmlContent());
});
});
</script>
</head>
<body>
<div class="random">
</div>
<div class="random">
</div>
</body>
</html>
If you don't mind the script tag remaining in place you can use something as simple as document.write().
myfile1.js:
document.write("<p>some html generated inline by script</p>");
It will do exactly what you need.

how do I automatically execute javascript?

how do I automatically execute javascript?
I know of <body onLoad="">, but I just thought maybe there is another way to do it?
html:
<html><head></head><body><div id="test"></div></body></html>
javascript:
<script>(function(){var text = document.getElementById('test').innerHTML;var newtext = text.replace('', '');return newtext;})();</script>
I wanna get the text within "test", replace certain parts, and then output it to the browser.
Any ideas on how to do it? I'd appreciate any help. Thanks.
If you don't want to use <body onload> which is good choice in terms of obtrusive javascript, you can separate that and put you code like this:
window.onload = function(){
// your code here
};
Alternative:
Place your javascript code at the bottom of the page.
Place the script at the bottom of the page, outside the closing body tag..
It's REALLY easy! If you have a script in your "head" block, with no function id, it will run automatically as soon as the web page loads. For example:
<head>
<meta charset="UTF-8">
<title>Redirection to www.mywebsite.org</title>
<!-- This script initiates an automatic web page redirection, as the page is loaded -->
<script type="text/javascript">
window.location = "http://www.mywebsite.com/"
</script>
</head>
If you don't want to use jQuery, use native window.onload method:
<script type="text/javascript">
function ReplaceText() {
document.getElementById('test').innerHTML = document.getElementById('test').innerHTML.replace(/abc/g, "def");
}
window.onload = ReplaceText;
</script>
Used on the code:
<div id="test">abc abc</div>
Will give this output:
def def
A quick way, if you just want to debug, would be move what you want to execute outside of a function.
<script type="text/javascript">
var text = document.getElementById('test').innerHTML;
var newtext = text.replace('', '');
alert(newtext);
</script>
NB. I'm not sure what you hope to achieve with text.replace('', '') ?

Categories