Uncaught ReferenceError: videojs is not defined. videojs async loading - javascript

So i have a js file as follows:-
(function(){
console.log("Starting Point");
// Creating and Appending scripts dynamically
function createScript(src) {
console.log("script for js");
var script = document.createElement('script');
script.src = src;
document.getElementsByTagName('head')[0].appendChild(script);
}
// End script tags Here
function createLink(href) {
console.log("script for links");
var link = document.createElement('link');
link.href = href;
link.rel = "stylesheet";
link.type = "type/css";
document.getElementsByTagName('head')[0].appendChild(link);
}
// DIV 1
// Create a main Div to hold everything
createScript('http://vjs.zencdn.net/4.7.1/video.js');
createScript('lib/videojs-contrib-ads/videojs.ads.js');
createScript('lib/vast-client.js');
createScript('videojs.vast.js');
createLink('http://vjs.zencdn.net/4.7.1/video-js.css');
createLink('lib/videojs-contrib-ads/videojs.ads.css');
createLink('videojs.vast.css');
console.log("Create mainDiv");
var mainDiv = document.createElement('div');
mainDiv.id = 'ad_placement';
// mainDiv.style.float = "right";
var currentScript = document.currentScript;
currentScript.parentElement.insertBefore(mainDiv, currentScript);
// document.body.appendChild(mainDiv);
console.log("End MainDiv");
// End main Div here
// DIV 2
// Div to hold the video
console.log("Create innerDiv")
var divContainer = document.createElement('div');
divContainer.class = 'example-video-container';
divContainer.style.display = 'inline-block';
mainDiv.appendChild(divContainer);
console.log("Create innerDiv")
// End parent Div here (parent of video div/tag)
// Video Player Below
// Create the video tag for html video player
console.log("Video Creation Started");
var video = document.createElement('video');
video.id = 'vid2';
video.width = 300;
video.height = 250;
video.class = 'video-js vjs-default-skin';
video.autoplay = true;
video.controls = true;
video.muted = true;
video.preload = 'auto';
video.poster = "http://www.jqueryscript.net/images/Simplest-Responsive-jQuery-Image-Lightbox-Plugin-simple-lightbox.jpg";
//video.data-setup = '{}';
// Function to create sources for video
function addSourceToVideo(element, src, type) {
var source = document.createElement('source');
source.src = src;
source.type = type;
element.appendChild(source);
}
addSourceToVideo(video, 'http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4', 'video/mp4');
addSourceToVideo(video, 'http://video-js.zencoder.com/oceans-clip.mp4', 'video/webm');
addSourceToVideo(video, 'http://video-js.zencoder.com/oceans-clip.mp4', 'video/ogg');
console.log("Video Creation End");
console.log("Para Started");
var paragraph = document.createElement('p');
paragraph.innerHTML = "Video PlayBack Not Supported";
video.appendChild(paragraph);
video.load();
//video.play();
divContainer.appendChild(video);
console.log("Para end");
// Video player creation ends here
console.log("Before calling videojs");
var vid2 = videojs('vid2');
console.log("After calling videojs");
vid2.muted(true);
vid2.ads({
timeout: 5000
});
vid2.vast({
url: 'vast_tag_url'
});
vid2.on('readyforpreroll', function() {
vid2.ads.startLinearAdMode();
vid2.one('ended', function() {
vid2.ads.endLinearAdMode();
console.log("ad finished");
document.getElementById('adPlacement').innerHTML="<img src='https://wallazee.global.ssl.fastly.net/images/variant/20140109-11d5e6789afea899c324f5d4cbfa00eca24c58c8b790e1d6305c36e-1024.png' width=300 height=250 border=0/>";
});
});
vid2.on('adtimeout', function() {
console.log("timout happened")
document.getElementById('adPlacement').innerHTML="<img src='https://wallazee.global.ssl.fastly.net/images/variant/20140109-11d5e6789afea899c324f5d4cbfa00eca24c58c8b790e1d6305c36e-1024.png' width=300 height=250 border=0/>";
});
console.log("End of file");
})();
So i am getting video.js not defined error when i include this file in html page. Need a javascript solution. (I can't use jquery)
Where am i wrong.it works on normal html page when we have css and js in head then a div with video and js functions in body.
when i created a js and imported then its a problem

Related

How to call function on keyup - Javascript

I am triying to create mathjax output to png file
I have created a JSFiddle here
I used code like below, I have an html code like
function myFunction(eqn){
window.MathJax = {
jax: ["input/TeX", "output/SVG"],
extensions: ["tex2jax.js", "MathMenu.js", "MathZoom.js"],
showMathMenu: false,
showProcessingMessages: false,
messageStyle: "none",
SVG: {
useGlobalCache: false
},
TeX: {
extensions: ["AMSmath.js", "AMSsymbols.js", "autoload-all.js"]
},
AuthorInit: function() {
MathJax.Hub.Register.StartupHook("End", function() {
var mj2img = function(texstring, callback) {
var input = texstring;
var wrapper = document.createElement("div");
wrapper.innerHTML = input;
var output = { svg: "", img: ""};
MathJax.Hub.Queue(["Typeset", MathJax.Hub, wrapper]);
MathJax.Hub.Queue(function() {
var mjOut = wrapper.getElementsByTagName("svg")[0];
mjOut.setAttribute("xmlns", "http://www.w3.org/2000/svg");
// thanks, https://spin.atomicobject.com/2014/01/21/convert-svg-to-png/
output.svg = mjOut.outerHTML;
var image = new Image();
image.src = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(output.svg)));
image.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext('2d');
context.drawImage(image, 0, 0);
output.img = canvas.toDataURL('image/png');
callback(output);
};
});
}
mj2img(eqn, function(output){
const t = document.getElementById("target"); const i = document.createElement('img'); i.src = output.img; t.append(i);
});
});
}
};
}
(function(d, script) {
script = d.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.onload = function() {
// remote script has loaded
};
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js';
d.getElementsByTagName('head')[0].appendChild(script);
}(document));
<textarea onkeyup="myFunction(this.value)"></textarea>
<div id="target"></div>
How to display image when keyup a form containing textarea?
Here is a working version of above code by giving direct value.
standard pattern for keyup Event listener
document.getElementById("target").onkeyup = function() {funName()};
According to your specific problem. I'm not pretty sure where do you want to apply it

Video Js is not defined when call in external js file

(function () {
// Creating and Appending scripts dynamically
function createScript(src) {
var script = document.createElement('script');
script.src = src;
document.getElementsByTagName('head')[0].appendChild(script);
}
// End script tags Here
function createLink(href) {
var link = document.createElement('link');
link.href = href;
link.rel = "stylesheet";
link.type = "type/css";
document.getElementsByTagName('head')[0].appendChild(link);
}
createLink('http://vjs.zencdn.net/4.12/video-js.css');
createScript('http://vjs.zencdn.net/4.12/video.js');
createLink('http://localhost/projects/test/bin/videojs.vast.vpaid.min.css');
createScript('http://localhost/projects/test/bin/videojs_4.vast.vpaid.min.js');
createScript('http://localhost/projects/test/bin/es5-shim.js');
createScript('http://localhost/projects/test/bin/ie8fix.js');
// DIV 2
// Div to hold the video
var divContainer = document.createElement('div');
divContainer.class = 'example-video-container';
divContainer.style.display = 'inline-block';
document.getElementById("video3438445[CB]").appendChild(divContainer);
// End parent Div here (parent of video div/tag)
// Video Player Below
// Create the video tag for html video player
var video = document.createElement('video');
video.id = 'video';
/*video.width = 300;
video.height = 250;*/
video.className = 'video-js vjs-default-skin';
video.autoplay = true;
video.controls = true;
video.muted = true;
video.preload = 'auto';
video.poster = "http://vjs.zencdn.net/v/oceans.png";
//video.data-setup = '{}';
// Function to create sources for video
function addSourceToVideo(element, src, type) {
var source = document.createElement('source');
source.src = src;
source.type = type;
element.appendChild(source);
}
addSourceToVideo(video, 'http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4', 'video/mp4');
addSourceToVideo(video, 'http://video-js.zencoder.com/oceans-clip.mp4', 'video/webm');
addSourceToVideo(video, 'http://video-js.zencoder.com/oceans-clip.mp4', 'video/ogg');
var paragraph = document.createElement('p');
paragraph.innerHTML = "Video PlayBack Not Supported";
video.appendChild(paragraph);
video.load();
//video.play();
divContainer.appendChild(video);
// Video player creation ends here
var vt = 'Vast_tag_url';
var vpaidPath = 'http://localhost/projects/test/bin/VPAIDFlash.swf';
setTimeout(myFunction, 1000);
function myFunction() {
var player = videojs(
"video", {
plugins: {
"vastClient": {
"adTagUrl": vt,
"adCancelTimeout": 15000,
"adsEnabled": true,
"playAdAlways": true,
"vpaidFlashLoaderPath": vpaidPath
}
}
})
}
})();
It works on normal HTML page when we have CSS and JS in head then a div with video and JS functions in body. But when I created a JS file and included it by javascript then it is not working.
Please suggest me what I am doing wrong.
Thanks so much for your response. My issue has been resolved. I used following code for this.
function loadScriptSync(src) {
var s = document.createElement('script');
s.src = src;
s.type = "text/javascript";
s.async = false; // <-- this is important
document.getElementsByTagName('head')[0].appendChild(s);
}
It will load js files synchronously.
The way you are loading the scripts is asynchronously.
You could either load them in the head directly, or implement a method that will listen to the loading events. Example below written in ES6.
function loadScript(src) {
return new Promise((onFulfilled, onRejected) => {
const script = document.createElement('script');
let loaded;
// set source path to load
script.setAttribute('src', src);
script.onreadystatechange = script.onload = () => {
if (!loaded) {
onFulfilled(script);
}
loaded = true;
};
script.onerror = function() {
// something went wrong
};
// append the given script
document.getElementsByTagName('head')[0].appendChild(script);
});
}
loadScript('http://url').then(() => {
// do something now that the script is loaded.
});
Now you will be sure that when the promise is fulfilled, the script is loaded successfully.

Display a loading icon while loading image

I would like to be able to display a GIF while the image is being loaded. Is this possible with the script I am using?
From what I understand I would use something like
$('#image').load { loadingimage.hide }
Here is my code:
$.get('http://192.168.1.69:8090/VirtualRadar/AirportDataThumbnails.json?icao=' + p.Icao + '&reg=' + p.Reg , function(res) {
var error = res.status;
if (error == "404") {
$("#image").attr('src', "placeholder.jpg");
$("#image2").attr('src', "placeholder.jpg");
$("#imageurl").attr('href', "//airport-data.com");
} else {
var imgUrl = res.data[0].image;
var imgHref = res.data[0].link;
$("#image").attr('src', imgUrl);
$("#image2").attr('src', imgUrl);
$("#imageurl").attr('href', imgHref);
}
})
Use the Image.onload attribute or attach an event listener.. load the loading wheel image first then display that while the larger image is loading...
function loadImage(src){
return new Promise(done=>{
var i = new Image();
i.onload = ()=>done(i);
i.src = src;
});
}
const loadImgSrc = "https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif";
const bigImgSrc = "https://www.gannett-cdn.com/-mm-/4252e7af1a3888197136b717f5f93523f21f8eb2/r=x1683&c=3200x1680/local/-/media/USATODAY/onpolitics/2012/10/03/bigbird-16_9.jpg";
loadImage(loadImgSrc).then(img=>{
img.style.maxWidth = "100%";
document.getElementById('myImg').appendChild(img);
loadImage(bigImgSrc).then(img=>{
img.style.maxWidth = "100%";
document.getElementById('myImg').innerHTML = '';
document.getElementById('myImg').appendChild(img);
});
})
<div id=myImg></div>

Webaudio, play sound twice

I am experimenting with WebAudio and I am loading in a sound with the following javascript code.
function playAudio(){
var audio = document.getElementById('music');
var audioContext = new webkitAudioContext();
var analyser = audioContext.createAnalyser();
var source = audioContext.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(audioContext.destination);
audio.play();
}
I also want to analyse the sound can visualise it with canvas, hence the analyser. It works fine the first time but if I run this function twice I get an error.
> playAudio(); // works fine, i can hear a sound
> playAudio(); // error
InvalidStateError: Failed to execute 'createMediaElementSource' on 'AudioContext': invalid HTMLMediaElement.
What is causing this error? I know that the error is caused by this line of code:
var source = audioContext.createMediaElementSource(audio);
I am creating a new audio context, so I would assume that I can re-use the same audio element in my html.
By creating the audio element dynamically (as shown in this fiddle, http://jsfiddle.net/ikerr/WcXHK/), I was able to play the song repeatedly.
function createAudioElement(urls) {
var audioElement = document.createElement("audio");
audioElement.autoplay = true;
audioElement.loop = false;
for (var i = 0; i < urls.length; ++i) {
var typeStr = "audio/" + urls[i].split(".").pop();
if (audioElement.canPlayType === undefined ||
audioElement.canPlayType(typeStr).replace(/no/, "")) {
var sourceElement = document.createElement("source");
sourceElement.type = typeStr;
sourceElement.src = urls[i];
audioElement.appendChild(sourceElement);
console.log("Using audio asset: " + urls[i]);
}
}
return audioElement;
}
var audioContext = new webkitAudioContext();
function playAudio(){
var audio = createAudioElement(['http://www.soundjay.com/button/button-1.mp3' ]);
if(audio){
var source = audioContext.createMediaElementSource(audio);
var analyser = audioContext.createAnalyser();
source.connect(analyser);
analyser.connect(audioContext.destination);
audio.play();
}
}
playAudio(); // works fine, i can hear a sound
playAudio();
//setTimeout(playAudio,2000);
Demo : http://jsfiddle.net/raathigesh/fueg3mk7/10/

Preloader for loading images

I am currently working on SVG SMIL animation in which I am using some .png and .gif files for easing my animation in IE. For this animation I am trying to get Preloader before animation and its other contents get loaded.
Problem is I am not getting that Preloader working properly. My .html page is getting loaded first and then preloader is starting... In Preloader also, I have used several preloaders available on the web. But they are not helpful for me.
Script and .html files loading time can be counted by domContentLoaded but for images. I dont know how to do that. If someone can suggest me a way that would be great.
here is code of preloader.js, I found on web:
$(document).ready(function () {
"use strict"
//indexOf support for IE8 and below.
if (!Array.prototype.indexOf){
Array.prototype.indexOf = function(elt /*, from*/){
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++){
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
//bgImg for holding background images in the page & img array for images present in the document(<img src="">).
var bgImg = [], img = [], count=0, percentage = 0;
//Creating loader holder.
$('<div id="loaderMask"><span>0%</span></div>').css({
position:"fixed",
top:0,
bottom:0,
left:0,
right:0,
background:'#fff'
}).appendTo('body');
//Using jQuery filter method we parse all elemnts in the page and adds background image url & images src into respective arrays.
$('*').filter(function() {
var val = $(this).css('background-image').replace(/url\(/g,'').replace(/\)/,'').replace(/"/g,'');
var imgVal = $(this).not('image').attr('xlink:href');
//Getting urls of background images.
if(val !== 'none' && !/linear-gradient/g.test(val) && bgImg.indexOf(val) === -1){
bgImg.push(val)
}
//Getting src of images in the document.
if(imgVal !== undefined && img.indexOf(imgVal) === -1){
img.push(imgVal)
}
});
//Merging both bg image array & img src array
var imgArray = bgImg.concat(img);
console.log(imgArray.length);
//Adding events for all the images in the array.
$.each(imgArray, function(i,val){
//Attaching load event
$("<image />").attr("xlink:href", val).bind("load", function () {
console.log('val'+val);
completeImageLoading();
});
//Attaching error event
$("<image />").attr("xlink:href", val).bind("error", function () {
imgError(this);
});
})
//After each successful image load we will create percentage.
function completeImageLoading(){
count++;
percentage = Math.floor(count / imgArray.length * 100);
console.log('percentage:'+percentage);
$('#loaderMask').html('<span>'+percentage + '%'+'</span>');
//When percentage is 100 we will remove loader and display page.
if(percentage == 100){
$('#loaderMask').html('<span>100%</span>')
$('#loaderMask').fadeOut(function(){
$('#loaderMask').remove()
})
}
}
//Error handling - When image fails to load we will remove the mask & shows the page.
function imgError (arg) {
$('#loaderMask').html("Image failed to load.. Loader quitting..").delay(3000).fadeOut(1000, function(){
$('#loaderMask').remove();
})
}
});
A little trick I do to ensure my or external data or images are loaded before I start executing my js code is, I create a div with display:none and fill it with all the tags that I need loaded.
<body>
<span id="loadingText">Loading...</span>
<div style="display:none">
<img src="pathtoimage1">
<img src="pathtoimage2">
<img src="pathtoimage3">
</div>
<script>
window.onload = function(){
//This gets called when all the items in that div has been loaded and cached.
document.getElementById("loadingText").style.display = "none";
}
</script>
</body>
I use this for preloading images for animations.
you can add and remove how many you load as needed.
<script language="javascript">function preloader() {
if (document.images) {
var img1 = new Image();
var img2 = new Image();
var img3 = new Image();
var img4 = new Image();
var img5 = new Image();
var img6 = new Image();
var img7 = new Image();
var img8 = new Image();
var img9 = new Image();
img1.src = "image link here";
img2.src = "image link here";
img3.src = "image link here";
img4.src = "image link here";
img5.src = "image link here";
img6.src = "image link here";
img7.src = "image link here";
img8.src = "image link here";
img9.src = "image link here";
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(preloader);</script>

Categories

Resources