How I can change this deprecated code document.write for improve pagespeed - javascript

I would like to improve a code that I have in the sidebar of wordpress, where what I want is that every time people enter randomly loads an image. At the moment with the code I have shown below it works, but when I put my page in google speed it says this:
Avoid use: document.write()
link = new Array();
link[0] = '<img src="" width="300" height="408"/>';
link[1] = '<img src="" width="300" height="408"/>';
link[2] = '<img src="" width="300" height="408"/>';
link[3] = '<img src="" width="300" height="408"/>';
random = Math.random() * (link.length);
random = Math.floor(random);
document.write(link[random]);
<div id="bloquewidget"></div>

There doesn't look to be any need for the array or randomness since the link HTMLs are all the same. Create an <a> with createElement, then use a CSS selector to insert it into the document at the appropriate point. You'll need some way to uniquely identify this <div> - use a class if it already has one, or give the div a class, such as link-container:
const a = document.createElement('a');
a.target = '_blank';
a.rel = 'noopener nofollow';
// do you want to add a non-empty src to the a here?
const img = a.appendChild(document.createElement('img'));
img.width = 300;
img.height = 408;
// do you want to add a non-empty src to the image here?
// insert <a> at the bottom of this div:
document.querySelector('.link-container').appendChild(a);

the
document.write(link[random]);
part can be replaced with:
document.body.innerHTML = document.body.innerHTML + link[random];
It is also worth looking into createElement for creating DOM objects like anchors.

Well I found another solution to my problem I leave the code here in case anyone else needs to put in a wordpress a widget with images that are randomly generated with their own link and not using the deprecated code document.write
<div id="bloquewidget">
<a id="a" rel="nofollow noopener noreferrer" target="_blank"><img id="image" /></a>
<script type='text/javascript'>
var images =
[
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
imageUrlPair = { ImgSrc:"your URL image here", Href:"your URL here" },
]
function randImg() {
var size = images.length;
var x = Math.floor(size * Math.random());
var randomItem = images[x];
document.getElementById('image').src = randomItem.ImgSrc;
document.getElementById('a').href = randomItem.Href;
document.getElementById("image").height = "408";
document.getElementById("image").width = "300";
}
randImg();
</script>

Related

Get src type of img or video tag (not extension)?

Say I have an image tag such as this:
<img src="smiley.gif" alt="Smiley face" height="42" width="42">
I know I can get the src by using myImageEl.src.
However, how do I get the type of the src (.gif in this case)?
Basically, my end goal is to pass the file type to window.URL.createObjectUrl()
let src = imageEl.src;
let srcType = src.type; // Here I need to get the type
let videoFile = new Blob([src], {type: srcType});
let videoSrc = window.URL.createObjectURL(videoFile);
var imgSrc = 'image.jpeg';
var ext = imgSrc.replace(/^.*\./, '')
I am not very good with regex, but using regex to fetch the extension of the image or video is the a good way of accomplishing this task.
For precision sake you could compare ext with a predeifined set of array
imgTag = ['jpg', 'jpeg', 'gif', 'png'];
vidTag = ['mp4', '3gp']
then you can compare using a forEach loop
From your tags I noticed you want to access image source type from javascript, if so you can use following codes base on what attributes we have for that image element:
for example if image element has id :
var imageElement = document.getElementById(id);
var imgsrc = imageElement.src;
var imgType = imgsrc.split('.').pop();
imgType will be the type of your image.
And if your image element doesn't have id, you can use document.getElementsByTagName("img") instead of document.getElementById(id) and code will look like this
var imageElement = document.getElementsByTagName("img");
var imgsrc = imageElement.src;
var imgType = imgsrc.split('.').pop();

How to display dynamic url image in html from which created by javascript

I am trying to display the image directly in HTML through a dynamic link I generated by Javascript.
function dynamicUrl() {
var url = "http://xxx.xxx.xxx" + dynamic_variables + ".jpg";
return url;}
Most of my research, people display image by click on buttons
or what I can do for now is link to the image.
test
Anyone know how to directly display the image using the dynamic URL?
Thanks!
Dynamic create DOM for example:
function dynamicUrl() {
var url = "https://is1-ssl.mzstatic.com/image/thumb/Purple111/v4/dd/95/7e/dd957e3a-abd3-da8a-2211-726a67108938/source/256x256bb.jpg";
return url;
}
var img = document.createElement("img");
img.src = dynamicUrl();
document.body.appendChild(img);
Manipulate DOM to dynamic change img url:
function dynamicUrl() {
var url = "https://www.62icon.com/client/assets/img/like-icon.svg";
var img = document.getElementById('imageid');
img.src = url;
}
<div>
<p>Image goes here</p>
<button onclick="dynamicUrl()">Change Image</button>
</div>
<img id="imageid" src="https://is1-ssl.mzstatic.com/image/thumb/Purple111/v4/dd/95/7e/dd957e3a-abd3-da8a-2211-726a67108938/source/256x256bb.jpg" />
Adding a id for the link element
<a id="link" href="">test</a>
Using click event of link element
var link = document.getElementById("link");
link.onclick = function goToDynamicUrl() {
var url = "https://image.flaticon.com/teams/new/1-freepik.jpg";
window.location.href = url;
}
Here is another method:
<div id="dimg">Here add image</div>
<script>
var dimg = document.getElementById('dimg');
function addImg(dv){
dimg.innerHTML ='<img src="http://xxx.xxx.xxx'+ dv +'.jpg'" >';
}
addImg('imgname');
</script>

add javascript variable in image url

My Random Number Generate code is
var randomnumber=Math.floor(Math.random()*99999)
Now I want to put this variable output in a image scr url..
Here is my url
<img src="http://www.myexample.com/get/image.php?vcid=14851&t=481" alt="" id="imge"/>
So what will my code?
<img src="http://www.myexample.com/get/image.php?vcid='+ randomnumber +'&t=481" alt="" id="imge"/>
??
Please help me
In pure Javascript you could do it like
var randomNumber = 1;
var image = document.getElementById("imageId");
var imageSrc = image.getAttribute("src");
image.setAttribute("src", imageSrc + randomNumber);
To put your number at the correct place you could use some string split functions, but since the order of query strings don't matter you should just put your vcid query at the end.
Try adding this in your <script>:
document.getElementById("imge").src = "http://www.myexample.com/get/image.php?vcid=" + randomnumber + "&t=481";
I'd personally suggest:
var img = document.getElementById('imge');
img.src = img.src.replace(/vcid=(\d+)/, function(){
return randomnumber=Math.floor(Math.random()*99999);
});
// purely to see the src has been changed, this is *not* relevant or required
img.title = img.src;
<img src="http://www.myexample.com/get/image.php?vcid=14851&t=481" alt="" id="imge"/>
References:
JavaScript Regular Expressions.
String.replace().

Get Image Source URLs from a Different Page Using JS

Everyone:
I'm trying to grab the source URLs of images from one page and use them in some JavaScript in another page. I know how to pull in images using JQuery .load(). However, rather than load all the images and display them on the page, I want to just grab the source URLs so I can use them in a JS array.
Page 1 is just a page with images:
<html>
<head>
</head>
<body>
<img id="image0" src="image0.jpg" />
<img id="image1" src="image1.jpg" />
<img id="image2" src="image2.jpg" />
<img id="image3" src="image3.jpg" />
</body>
</html>
Page 2 contains my JS. (Please note that the end goal is to load images into an array, randomize them, and using cookies, show a new image on page load every 10 seconds. All this is working. However, rather than hard code the image paths into my javascript as shown below, I'd prefer to take the paths from Page 1 based on their IDs. This way, the images won't always need to be titled "image1.jpg," etc.)
<script type = "text/javascript">
var days = 730;
var rotator = new Object();
var currentTime = new Date();
var currentMilli = currentTime.getTime();
var images = [], index = 0;
images[0] = "image0.jpg";
images[1] = "image1.jpg";
images[2] = "image2.jpg";
images[3] = "image3.jpg";
rotator.getCookie = function(Name) {
var re = new RegExp(Name+"=[^;]+", "i");
if (document.cookie.match(re))
return document.cookie.match(re)[0].split("=")[1];
return'';
}
rotator.setCookie = function(name, value, days) {
var expireDate = new Date();
var expstring = expireDate.setDate(expireDate.getDate()+parseInt(days));
document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/";
}
rotator.randomize = function() {
index = Math.floor(Math.random() * images.length);
randomImageSrc = images[index];
}
rotator.check = function() {
if (rotator.getCookie("randomImage") == "") {
rotator.randomize();
document.write("<img src=" + randomImageSrc + ">");
rotator.setCookie("randomImage", randomImageSrc, days);
rotator.setCookie("timeClock", currentMilli, days);
}
else {
var writtenTime = parseInt(rotator.getCookie("timeClock"),10);
if ( currentMilli > writtenTime + 10000 ) {
rotator.randomize();
var writtenImage = rotator.getCookie("randomImage")
while ( randomImageSrc == writtenImage ) {
rotator.randomize();
}
document.write("<img src=" + randomImageSrc + ">");
rotator.setCookie("randomImage", randomImageSrc, days);
rotator.setCookie("timeClock", currentMilli, days);
}
else {
var writtenImage = rotator.getCookie("randomImage")
document.write("<img src=" + writtenImage + ">");
}
}
}
rotator.check()
</script>
Can anyone point me in the right direction? My hunch is to use JQuery .get(), but I've been unsuccessful so far.
Please let me know if I can clarify!
Try this.
<script>
$.get('http://path/to/page/1', function(data) {
var imgs = $('<div/>').html(data).find('img');
imgs.each(function(i, img) {
alert(img.src); // show a dialog containing the url of image
});
});
</script>
I don't understand why you want to use cookies for this. You should get page1, find the images, and then use setInterval to update the src.
$.get('page1.html', function(data, status) { // get the page with the images
var parser = new DOMParser();
var xmldoc = parser.parseFromString(data, "text/html"); //turn it into a dom
var imgs = xmldoc.getElementsByTagName('img'); //get the img tags
var imageSrcs = Array.prototype.slice.call(imgs).map(function(img) {
return img.src; //convert them to an array of sources
});
setInterval(function() { // run this every 10 seconds
var imags = document.getElementsByTagName('img'); // find the images on this page
Array.prototype.slice.call(imgs).forEach(function(img) {
var imgSrc = Math.floor(Math.random()*imageSrcs.length); //get a random image source
img.src = imageSrcs[imgSrc]; //set this image to the src we just picked at random
});
}, 10000);
}, 'html');
why not use ajax? you could .load() the section of your external page that contains all of the images into a hidden container and then extrapolate the information you need through a callback.
external.html
<html>
....
<div id="imgContainer">
<img id="image0" src="image0.jpg" />
<img id="image1" src="image1.jpg" />
<img id="image2" src="image2.jpg" />
<img id="image3" src="image3.jpg" />
</div>
</html>
ajax.js
function ajaxContent(reg, extReg) {
var toLoad = 'external.html' + extReg;
function loadContent() {
$(reg).load(toLoad,'',getSrcPaths())
}
function getSrcPaths() {
$(reg + ' #image0').delay(200).fadeIn('slow');
$(reg + ' #image1').delay(200).fadeIn('slow');
// or however you want to store/display the images
}
}
Then onload just make a call to ajaxContent something like
<body onload="ajaxContent('#hiddenContainer','#imgContainer')">
....
</body>
This of course is not really relevant if your images are large or if page load is negatively affected. Although since you actually have the images now, you might even just display them rather than hide them. Depends on exactly how much you need to manipulate the originals I suppose.

Javascript parse html, modify anchor tags that contain images

I have a vague idea on howto do this but I hoped more experienced devs might have a simpler solution.
I have a sting of HTML code from a JSON feed and where an "a" tag exists with an images inside the "a" tag I want to modify and add attributes. example:
<a style="color:000;" href="images/image.jpg">
<img width="100" height="20" src="images/image_thumb.jpg" />
</a>
I would like to change it to be:
<a style="color:000;" href="images/image.jpg" rel="lightbox" >
<img width="100" height="20" decoy="images/image_thumb.jpg" />
</a>
So adding an attribute to the "a" tag and modifying an attribute in the "img" tag. There maybe multiple links within the HTML code some with and without images and other HTML code surrounding them.
To be clear this is NOT modifying HTML already rendered on the page, this is modifying a string of code before it gets rendered.
To be extremely clear here is the JSON feed in question: http://nicekiwi.blogspot.com/feeds/posts/default?alt=json
The HTML code that contains the tags are found at "feed > entry > content > $t"
Am currently working with Mootools 1.3
Any ideas? Thanks.
First, put it in a new element that does not exist on the page, then modify it as usual:
var container = new Element("div", { html: yourHTML });
container.getElements("a img").forEach(function(img){
var link = img.getParent("a");
img.decoy = img.src;
img.removeAttribute("src");
link.rel = "lightbox";
});
Demo here: http://jsfiddle.net/XDacQ/1/
In straight JS
var a = document.createElement('div');
// put your content in the innerHTML like so
a.innerHTML = '<a style="color:000;" href="images/image.jpg"><img width="100" height="20" src="images/image_thumb.jpg" /></a>';
var b = a.firstChild;
b.rel = 'lightbox';
var c = b.firstChild;
c.setAttribute('decoy', c.src);
c.src = null;
// now you have your a tag
var newA = a.innerHTML;
Dumbest regexp
var string = '<a style="color:000;" href="images/image.jpg">="images/image_thumb.jpg" /></a>',
text = '';
text = string.replace('href', 'rel="lightbox" href');
text = text.replace('src', 'decoy');

Categories