How would I add this JS into a HTML page? - javascript

I've got this JS code, which should load another image if the one it tries to load first takes too long:
var image = new Image();
image.src = "firstimage.jpg?cookie=" + encodeURI( document.cookie );
setTimeout
(
function()
{
if ( !image.complete || !image.naturalWidth )
{
image.src = "backupimage.jpg";
}
},
1000
);
I can't figure out how to put it into my HTML though (I only have VERY basic HTML skills!) Would anybody be able to show me?
Many thanks in advance

Assuming that you have added the Javascript on the page, you can inject the image to the body of the page using document.body.appendChild(image).
Or, if you wanted to inject the image into an element other than body, you could use element.appendChild(image).
var image = new Image();
image.src = "//placehold.it/300";
setTimeout
(
function()
{
if ( !image.complete || !image.naturalWidth )
{
image.src = "//placehold.it/200";
}
},
5000
);
document.body.appendChild(image);
// document.getElementById("myDiv").appendChild(image);
<div id="myDiv"></div>

HTML <script> tag
To add javascript or other scripts, use the <script> tags:
<script>
//code here
</script>
But do be aware that if any HTML elements are accesed with your JS, you must place the script after them so that they are loaded and exist (or use a delaying function on the document load).
Check the documentation

You can use the HTML <script> Tag.
The <script> tag is used to define a client-side script (JavaScript).
You use it like this:
<script>
//write your script here
</script>
Or create a function on load like this:
window.onload = function() {
yourFunction(param1, param2);
};

Related

Show LOADING in innerHTML while object is being loaded

I have following JavaScript function that load contents return by contacts.php into DIV id contacts-container, it takes a lot of time to complete the task. I want to show "LOADING.." text in the DIV id contacts-container while contents are being loaded.
function load_contacts() {
document.getElementById("contacts-container").innerHTML='<object type="text/html" data="contacts.php" ></object>';
}
I want solution in pure JavaScript.
What about some more JS?
function load_contacts() {
var el = document.createElement("object"),
target = document.getElementById("contacts-container")
target.innerHTML = "<span>Loading...</span>";
el.onload = function() {
target.firstChild.remove();
}
el.setAttribute("type","text/html");
el.setAttribute("data","contacts.php");
target.appendChild(el);
}
You can do with ajax. For this my suggestion, you must Jquery Ajax. For example,
$("#loadingElement").html("Loading");
$.load("#contacts-container",{},"contacts.php",function(){
$("#loadingElement").html("");
});

HTML JavaScript delay downloading img src until node in DOM

Hi I have markup sent to me from a server and I set it as the innerHTML of a div element for the purpose of traversing the tree, finding image nodes, and changing their src values. Is there a way to prevent the original src value from being downloaded?
Here is what I am doing
function replaceImageSrcsInMarkup(markup) {
var div = document.createElement('div');
div.innerHTML = markup;
var images = div.getElementsByTagName('img');
images.forEach(replaceSrc);
return div.innerHTML;
}
The problem is that in browsers as soon as you do:
var img = document.createElement('img'); img.src = 'someurl.com' the browser fires off a request to someurl.com. Is there a way to prevent this without resorting to parsing the markup myself? If there is in no other way does anyone know a good way of parsing the markup with as little code as possible to accomplish my goal?
I know you are already happy with your solution, but I think it would be worth sharing a safe method for future users.
You can now simply use the DOMParser object to generate an external document from your HTML string, instead of using a div created by your current document as container.
DOMParser specifically avoids the pitfalls mentioned in the question and other threats: no img src download, no JavaScript execution, even in elements attributes.
So in your case you can safely do:
function replaceImageSrcsInMarkup(markup) {
var parser = new DOMParser(),
doc = parser.parseFromString(markup, "text/html");
// Manipulate `doc` as a regular document
var images = doc.getElementsByTagName('img');
for (var i = 0; i < images.length; i += 1) {
replaceSrc(images[i]);
}
return doc.body.innerHTML;
}
Demo: http://jsfiddle.net/94b7gyg9/1/
Note: with your current code, browsers will still try downloading the resource initially specified in your img nodes src attribute, even if you change it before the end of JS execution. Trace network transactions in this demo: http://jsfiddle.net/94b7gyg9/
Rather than append the new markup to the DOM before you change the img sources, create an element, set it's inner HTML, change the source of the images and then finally, append the changed markup to the page.
Here's a fully-worked sample.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
//function allByClass(className,parent){return (parent == undefined ? document : parent).getElementsByClassName(className);}
function allByTag(tagName,parent){return (parent == undefined ? document : parent).getElementsByTagName(tagName);}
function newEl(tag){return document.createElement(tag);}
//function newTxt(txt){return document.createTextNode(txt);}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
byId('goBtn').addEventListener('click', onGoBtnClick, false);
}
var dummyString = "<img src='img/girl.png'/><img src='img/gfx07.jpg'/>";
function onGoBtnClick(evt)
{
var div = newEl('div');
div.innerHTML = dummyString;
var mImgs = allByTag('img', div);
for (var i=0, n=mImgs.length; i<n; i++)
{
mImgs[i].src = "img/murderface.jpg";
}
document.body.appendChild(div);
}
</script>
<style>
</style>
</head>
<body>
<button id='goBtn'>GO!</button>
</body>
</html>
You could directly parse the markup string using a regex to replace the img src. Searching for all the img src urls in the string and then replacing them with the new url.
var regex = /<img[^>]+src="?([^"\s]+)"?\s*\/>/g;
var imgUrls = [];
while ( m = regex.exec( markup ) ) {
imgUrls.push( m[1] );
}
imgUrls.forEach(function(url) {
markup = markup.replace(url,'new-url');
});
Another solution might be, if you have access to it, to set the all the img src to an empty string, and put the url in in a data-src attribute. Having your markup string look like something like this
markup = '
';
Then setting this markup to your div.innerHTML won't trigger any download from the browser. And you can still parse it using regular DOM selector.
div.innerHTML = markup;
var images = div.getElementsByTagName('img');
images.forEach(function(img){
var oldSrc = img.getAttribute('data-src');
img.setAttribute('src', 'new-url');
});

How to generate dynamic Image tags by jquery

I have fetched json through
<script>
function getjs()
{
var script =document.createElement("script");
script.setAttribute("type","text/javascript");
script.setAttribute("src","http://localhost:8080/vigs/f4json?user=3&callback=gr");
document.body.appendChild(script);
}
var i=0;
function gr(data)
{
for(i=0;i<data.size;i++)
{
document.getElementById('w').innerHTML =data.itemr[i].itmurl;
}
}
</script>
so, after fetching the urls it simply displays url of images in my div. I just confused how to write up code in jquery for same above task but also display images (by generating dynamix image tag appended to next one by one based on size in div) in my div with id mydiv.Or any alternative ?
your help would be appreciated..
thanks
Using JavaScript
function gr(data)
{
var w = document.getElementById('w');
for(i=0;i<data.itemr.length;i++)
{
var img = document.createElement('img');
img.src = data.itemr[i].itmurl;
w.appendChild(img);
}
}
$("<img>").attr("src", data.itemr[i].itmurl).appendTo($("#w"));

How to force a script reload and re-execute?

I have a page that is loading a script from a third party (news feed). The src url for the script is assigned dynamically on load up (per third party code).
<div id="div1287">
<!-- dynamically-generated elements will go here. -->
</div>
<script id="script0348710783" type="javascript/text">
</script>
<script type="javascript/text">
document.getElementById('script0348710783').src='http://oneBigHairyURL';
</script>
The script loaded from http://oneBigHairyURL then creates and loads elements with the various stuff from the news feed, with pretty formatting, etc. into div1287 (the Id "div1287" is passed in http://oneBigHairyURL so the script knows where to load the content).
The only problem is, it only loads it once. I'd like it to reload (and thus display new content) every n seconds.
So, I thought I'd try this:
<div id="div1287">
<!-- dynamically-generated elements will go here. -->
</div>
<script id="script0348710783" type="javascript/text">
</script>
<script type="javascript/text">
loadItUp=function() {
alert('loading...');
var divElement = document.getElementById('div1287');
var scrElement = document.getElementById('script0348710783');
divElement.innerHTML='';
scrElement.innerHTML='';
scrElement.src='';
scrElement.src='http://oneBigHairyURL';
setTimeout(loadItUp, 10000);
};
loadItUp();
</script>
I get the alert, the div clears, but no dynamically-generated HTML is reloaded to it.
Any idea what I'm doing wrong?
How about adding a new script tag to <head> with the script to (re)load? Something like below:
<script>
function load_js()
{
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.src= 'source_file.js';
head.appendChild(script);
}
load_js();
</script>
The main point is inserting a new script tag -- you can remove the old one without consequence. You may need to add a timestamp to the query string if you have caching issues.
Here's a method which is similar to Kelly's but will remove any pre-existing script with the same source, and uses jQuery.
<script>
function reload_js(src) {
$('script[src="' + src + '"]').remove();
$('<script>').attr('src', src).appendTo('head');
}
reload_js('source_file.js');
</script>
Note that the 'type' attribute is no longer needed for scripts as of HTML5. (http://www.w3.org/html/wg/drafts/html/master/scripting-1.html#the-script-element)
Creating a new script tag and copying the contents of the existing script tag, and then adding it, works well.
var scriptTag = document.createElement('script');
scriptTag.innerText = "document.body.innerHTML += 'Here again ---<BR>';";
var head = document.getElementsByTagName('head')[0];
head.appendChild(scriptTag);
setInterval(function() {
head.removeChild(scriptTag);
var newScriptTag = document.createElement('script');
newScriptTag.innerText = scriptTag.innerText;
head.appendChild(newScriptTag);
scriptTag = newScriptTag;
}, 1000);
This won't work if you expect the script to change every time, which I believe is your case. You should follow Kelly's suggestion, just remove the old script tag (just to keep the DOM slim, it won't affect the outcome) and reinsert a new script tag with the same src, plus a cachebuster.
Small tweak to Luke's answer,
function reloadJs(src) {
src = $('script[src$="' + src + '"]').attr("src");
$('script[src$="' + src + '"]').remove();
$('<script/>').attr('src', src).appendTo('head');
}
and call it like,
reloadJs("myFile.js");
This will not have any path related issues.
Use this function to find all script elements containing some word and refresh them.
function forceReloadJS(srcUrlContains) {
$.each($('script:empty[src*="' + srcUrlContains + '"]'), function(index, el) {
var oldSrc = $(el).attr('src');
var t = +new Date();
var newSrc = oldSrc + '?' + t;
console.log(oldSrc, ' to ', newSrc);
$(el).remove();
$('<script/>').attr('src', newSrc).appendTo('head');
});
}
forceReloadJS('/libs/');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
I know that is to late, but I want to share my answer.
What I did it's save de script's tags in a HTML file,
locking up the scripts on my Index file in a div with an id, something like this.
<div id="ScriptsReload"><script src="js/script.js"></script></div>
and when I wanted to refresh I just used.
$("#ScriptsReload").load("html_with_scripts_tags.html", "", function(
response,
status,
request
) {
});

how to load a picture from .js file to html?

I have a file called src.js which has all the scripts for my html page.
now on my html page I am using this :
<script language="javascript" src="src.js">
</script>
to call the .js file to use it.
I am not sure how to set up the images links in the .js file or how to call them in the .html file
I need a simple answer please :)
You need to have a placeholder for your images in the HTML otherwise you would need to dynamically modify the HTML DOM structure.
As for using variables for image links, refer to the code below which pre-loads the images.
if (document.images)
{
preload_image_object = new Image();
// set image url
image_url = new Array();
image_url[0] = "http://mydomain.com/image0.gif";
image_url[1] = "http://mydomain.com/image1.gif";
image_url[2] = "http://mydomain.com/image2.gif";
image_url[3] = "http://mydomain.com/image3.gif";
var i = 0;
for(i=0; i<=3; i++)
preload_image_object.src = image_url[i];
}
The browser must have the document.images attribute defined.
<div id="_images"></div>
<script>
var images = { // images with properties
image1 : {url:'http://image1',property:'value'},
image2 : {url:'http://image2',props:[],else:'val'}
}
for(var i in images){
var image = new Image();
image.src = images[i].url;
// put image anywhere you want
document.getElementById('_images').appendChild(image)
}
</script>

Categories

Resources