After my site loaded, I want to delay the below javascript for 10 seconds
script:
<script type="text/javascript" id="io258wer15cfg789as69th07er64hziq" src="//mysite.domain.com/script.php?id=io258wer15cfg789as69th07er64hziq" defer></script>
i tried this but not working:
<script
setTimeout(
function(){
type="text/javascript"
id="io258wer15cfg789as69th07er64hziq"
src="//mysite.domain.com/script.php?id=io258wer15cfg789as69th07er64hziq"
defer }
,10000)>
</script>
You need to add it using createElement. So that it will inject after 10s.
document.addEventListener("DOMContentLoaded", function(event) {
setTimeout(addScript, 1000)
});
function addScript() {
script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.onload = function() {
console.log("Added Script");
};
script.src = 'https://foo.com/bar.js';
document.getElementsByTagName('head')[0].appendChild(script);
}
Try this:
document.onload = function() {
window.setTimeout(function () {
var script = document.createElement('script');
script.async = true;
script.id = 'io258wer15cfg789as69th07er64hziq';
script.src = '//mysite.domain.com/script.php?id=io258wer15cfg789as69th07er64hziq';
document.querySelector('head').appendChild(script);
}, 10000);
};
Related
I'm trying to make a Stimulus controller which would access global Youtube Player API variable
Youtube Player API is lazy loading - it's class is loaded asynchronously
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
The problem is, that Stimulus doesn't want to access YT variable.
I tried to create a function, that loads script, and after it, runs given function, and imports it to stimulus
export function loadScript (url, callback) {
var script = document.createElement("script");
script.type = "text/javascript";
if (script.readyState) { // only required for IE <9
script.onreadystatechange = function () {
if (script.readyState === "loaded" || script.readyState === "complete") {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function () {
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
But as you can see, it only creates new script object, so Stimulus still won't be able to access it.
Is there a way in which I could make Stimulus access loaded script, and variables that are declared in it?
Here is a full controller code (don't mind bad practices, it's just a fast try):
import {
Controller
} from 'stimulus';
import $ from 'jquery';
export default class extends Controller {
static targets = ['collapseButton', 'player']
connect() {
this.initPlayer();
}
initPlayer() {
let player = $('#youtubePlayer');
// Code taken straight from https://developers.google.com/youtube/iframe_api_reference?hl=pl
player = new YT.Player(player, {
videoId: 'Va297erJjJ4',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
function onPlayerReady(event) {
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
}
}
<div class="youtube-player-modal" data-controller="youtubeplayer">
<div id="youtubePlayer"></div>
</div>
I wrote a solution to your problem here, there you must first call the ready function and then give the callback.
https://codesandbox.io/s/funny-browser-n3m3j?file=/src/Player.js
// loadScript.js
import Player from "./Player";
function loadScript(url, callback) {
var script = document.createElement("script");
script.type = "text/javascript";
if (script.readyState) {
// only required for IE <9
script.onreadystatechange = function () {
if (script.readyState === "loaded" || script.readyState === "complete") {
script.onreadystatechange = null;
callback();
}
};
} else {
//Others
script.onload = function () {
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
loadScript("https://www.youtube.com/iframe_api", new Player().initPlayer);
// Player.js
import { Controller } from "stimulus";
import $ from "jquery";
export default class extends Controller {
static targets = ["collapseButton", "player"];
connect() {
this.initPlayer();
}
initPlayer() {
let player = $("#youtubePlayer");
window.YT.ready(function () {
player = new window.YT.Player("youtubePlayer", {
height: "360",
width: "640",
videoId: "Va297erJjJ4",
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
});
});
function onPlayerReady(event) {
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
if (event.data === window.YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div
class="youtube-player-modal"
data-controller="youtubeplayer"
>
<div id="youtubePlayer"></div>
</div>
<script src="src/loadScript.js"></script>
</body>
</html>
I am loading my script files dynamically using this code,
<script type="text/javascript">
var newscript = document.createElement('script');
newscript.type = 'text/javascript';
newscript.src = '../static/js/jquery.js';
document.getElementsByClassName('container')[0].appendChild(newscript);
var newscript = document.createElement('script');
newscript.type = 'text/javascript';
newscript.src = '../static/js/report_app.js';
document.getElementsByClassName('container')[0].appendChild(newscript);
</script>
It throws error as,
Reference error: $ is not defined
in report_app.js.
I thought, jquery.js script must be loaded into the DOM when the next file, report_app.js is being parsed.
But the error shows, jquery.js is not executed. How to ensure one script file is loaded before running the next one?
It is because the script is added asynchronously, you can use the onload callback
function addScript(path, callback) {
var newscript = document.createElement('script');
newscript.type = 'text/javascript';
newscript.src = path;
newscript.onload = callback;
document.body.appendChild(newscript);
}
addScript('http://code.jquery.com/jquery-1.11.2.js', function () {
addScript('../static/js/report_app.js');
})
Demo: Fiddle
I am using google maps to get the coordinates of a location. My code is running exactly how I want it to however when I click save on the form I get the error in the above title.
Can anyone tell me where I am going wrong?
function init(){
//Calls the loadScript and initialize function and loads the Google Maps API
loadScript('//maps.googleapis.com/maps/api/js?APIKEY&callback=initialize');
}
function loadScript(src,callback){
//Adds the google maps script to the head of the HTML
alert('loading');
var script = document.createElement("script");
script.type = "text/javascript";
if(callback)script.onload=callback;
document.getElementsByTagName("head")[0].appendChild(script);
script.src = src;
}
Apparently all I needed was a try catch around the code:
function loadScript(src,callback){
//Adds the google maps script to the head of the HTML
try{
var script = document.createElement("script");
script.type = "text/javascript";
if(callback)script.onload=callback;
document.getElementsByTagName("head")[0].appendChild(script);
script.src = src;
}catch(e){
alert(e);
}
}
A common asynchronous download js function as follows.
But when the download fails, how to call the error function.
This function will be: function loadScript(url, callback, errcb).
function loadScript(url, callback){
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" || script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else { //Others: Firefox, Safari, Chrome, and Opera
script.onload = function(){
callback();
};
}
script.src = url;
document.body.appendChild(script);
}
I want to load external javascript file but I can't use AJAX requests because of same origin policy, and I have a code:
<script type="text/javascript">
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'test.js';
head.appendChild(script);
</script>
That is ok everywhere (Firefox, Chrome, Opera, IE9, IE6) but not in IE8, IE7. How can I make it work in IE8?
How about the old document.write('<script language="javascript" src="test.js"><\/script>'). Also you do not have to append to head you can use body to.
Try reading up about JsonP :)
I'm not sure why you had problems in IE, but the following worked in Firefox 4, IE6 and IE9 (i.e. the browsers I had available):
<html>
<head>
</head>
<body>
<script type="text/javascript">
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js';
head.appendChild(script);
var interval = window.setInterval(function() {
if (typeof($) !== "undefined") {
$("<p>it worked!</p>").appendTo(document.body);
window.clearInterval(interval);
}
}, 100);
</script>
</body>
</html>