I have this simple script that applies a chat widget to the website. How can I delay this script from running for about 4 seconds?
I tried looking up different solutions but nothing seemed to be the same circumstances.
https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
Wrap the entire script inside a named function block and call that from a setTimeout function:
(run the snippet and wait 4 seconds to see console message)
setTimeout(scriptCode, 4000);
function scriptCode (){
// place all script code here;
console.log("done");
} // end script
If you must reference the script from a named url, you can assemble a script tag in js and append it to the page after four seconds. Like this:
setTimeout(scriptCode, 4000);
function scriptCode (){
const scriptElement=document.document.createElement('script');
scriptElement.setAttribute("src", "http://scriptAddress.com");
scriptElement.setAttribute("async", "");
document.body.appendChild(scriptElement);
} // end script
The script tag will be added to the DOM after 4 seconds and will load and execute as normal
Related
I've the following function in jquery:
$(document).ready(function(){
$('.folder-action').bind('click', function location() {
if(parent.document.location.pathname!="/home.php"){
window.location.replace("home.php");
location();
});
//Other portion of code that need page has been loaded.
});
});
When the replace has been excecuted I need that all the elements of the page are already loaded to execute other portions of the code in the new page(home.php).
It've tryed with:
setTimeout(function() {location()}, 300);
But it still doesn't work. Is it possible to wait until all elements of the page are loaded?
You can not do it like that because once you used the replace function, the browser will leave your current page and won't execute anymore code.
The best thing to do is to put your Other portion of code in the $(document).ready of the home.php
I'm working to modify some content which is dynamically loaded via another script(let's call is script #1) onto my site. Script #1 loads some markup and content and I've been using the setTimeout() function to call my script (Script #2) using a delay of a few seconds, in order to wait to be sure that Script #1 has executed and the content is present in the DOM.
My issue is that Script#1 has different loading times, based on the server load and can be slow or fast depending on these factors, and right now, playing it safe with setTimeout() I'm often left with a second or two where my scripts are still waiting to be fired and Script #1 has already loaded the content.
How can I execute my script as soon as Script#1 successfully loads it's dynamic content?
I've found this post which does seem to address the same issue but using the setInterval function as #Matt Ball has laid out there doesn't work at all for some reason. I'm using the code below where 'div.enrollment' is meant to find in the DOM which is dynamically loaded and execute..
jQuery(window).load(function ($)
{
var i = setInterval(function ()
{
if ($('div.enrollment').length)
{
clearInterval(i);
// safe to execute your code here
console.log("It's Loaded");
}
}, 100);
});
Any help on guidance on this would be greatly appreciated! Thanks for your time.
It seems that the healcode.js is doing a lot of stuff. There is a whole lot of markup added to the <healcode-widget> tag.
I would try to add another tag with an id inside and test for its existence:
<healcode-widget ....><div id="healCodeLoading"></div></healcode-widget>
Test in an interval for the existence of healCodeLoading inside <healcode-widget>: (Assuming jQuery)
var healCodeLoadingInterval = setInterval(function(){
var healCodeLoading = jQuery('healcode-widget #healCodeLoading');
if (healCodeLoading.length == 0) {
clearInterval(healCodeLoadingInterval);
// Everything should be loaded now, so you can do something here
}
}, 100);
healcode.js should replace everything inside <healcode-widget></healcode-widget> during init. So, if your <div>-element is no longer inside, the widget has loaded and initialized.
Hope that helps.
If you just want to load some markup and content and then run some script afterwards, you can use jQuery. You should use something like the following in script#1 to run a function in script#2
$.get( "ajax/test.html", function( data ) {
// Now you can do something with your data and run other script.
console.log("It's Loaded");
});
The function is called, after ajax/test.html is loaded.
Hope that helps
I have a simple script that create a span in the page with some info taken by flash player API.
I tried 3 ways:
1) If I put the script with no onload or with:
( function (){ ...code here... }) ();
This doesn't load all my code correctly, particularly the player info part:
var spanSound=document.createElement('span');
Fls_div.appendChild(spanSound);
spanSound.appendChild(document.createTextNode(" audioLev:")); // --OK--
var player = window.document.getElementById('movie_player');
var spanQual= document.createElement('span');
spanQual.appendChild(document.createTextNode("-->" + player.getPlaybackQuality() )); // --NO--
But all youtube's comments are loaded.
2) I put all the code into:
window.onload = function(){ ...code here... }
This does load all my code correctly, BUT it doesn't load the youtube's comments...
3) finally I tried:
window.addEventListener("load", function(e) { ...code here... }, false);
this loads all correct, code and comments.
Why these 3 different behaviours ( particularly the 2) )?
1 - The code runs before anything else is loaded. When you try things like document.getElementById, the elements don't exist yet, so your code won't find it.
2 - You're replacing the window.onload function. Looks like the page already has a onload function (that takes care of loading the comments..?) and when you asign another function to it, the first one will be replace and won't run anymore.
3 - You're adding an event listener. You can have multiple event listeners in a page, when the event happens, all of the event listeners will execute (compared to window.onload, where you can have only one function execute).
I have the following problem: on a customer's homepage the navibar is loaded by javascript, but I need to change some URL's on it. If I just start my script on $(document).ready() it runs before the customers script and has no effect. I only can use setTimeout for my function to wait until the other script is ready, but it's not good or safe at all. I can't change anything on the website, only add a javascript - is there a way to time it after the other one?
You can use repeated setTimeout, in order to check if menu is accessible.
function check_menu(){
if(document.getElementById('my_menu')==null){
setTimeout('check_menu()',500);
} else {
//do some stuff
}
}
If you have information about the menu like the id or class, use the onLoad() jQuery method on the element. For example if the code is loading asynchronously, and you add the onload to one of the last elements it should fire after the content has finished.
$.post('AsyncCodeLoad.php', function(data) {
$('#lastElementToLoad').onLoad(RunMyFunction);
});
Or if you have no chance to insert your code into the async loading just add to the bottom of the </body>:
$('#lastElementToLoad').onLoad(RunMyFunction);
Just a thought.
Yes, add your script at the bottom of the <body /> tag to ensure it does not run until all other scripts have run. This will only work however if your customer is loading the nav links synchronously.
If the nav is being loaded asynchronously, use JS's setInterval to repeatedly check the contents of the nav for links. When you determine the links have been added, cancel your interval check and call your script's logic entry point.
Cheers
Fiddle: http://jsfiddle.net/iambriansreed/xSzjA/
JavaScript
var
menu_fix = function(){
var menu = $('#menu');
if(menu.length == 0) return;
clearInterval(menu_fix_int);
$('a', menu).text('Google Search').attr('href','http://google.com');
},
menu_fix_int = setInterval(menu_fix, 100);
HTML
<div id="menu">Bing Search</div>
I have banner code, which is not like images and hyperlinks. All I need is the javascript code that will refresh this code every 30 seconds without refreshing the rest of the page.
This banner code will be appear in chatroom. I would really appreciate any help.
The banner code:
<script language='JavaScript'
type='text/javascript'
src='xxxxxx/banner.php?uname=yyyy&type=2&rows=1' >
</script>
First thing you should do is wrap your code in a function. Trying to re-invoke an entire scripting file import is much more difficult than just invoking a function.
Once everything is wrapped in a function, you can use setTimeout to invoke the method. I would do something like this:
function drawBanner() {
// Do stuff to draw the banner.
// Make sure you handle the case that the
// banner is already present in the DOM!
}
function onDrawBannerTimer() {
// Set this function to fire again after 30 seconds.
// Note that this will fire it roughly every 30 seconds real-time.
// You can move this statement to after the drawBanner() call
// in order to make it 30 seconds between the end of one
// invocation and the start of the next.
setTimeout(onDrawBannerTimer, 30 * 1000);
drawBanner();
}
// Trigger the first invocation when the script is loaded.
onDrawBannerTimer();
you'll want to give that script tag an ID (such as id='dynScript') and then have another script block that does pretty much the following: [Note: I'm using jQuery]
<script>
$(document).ready(function(){
setTimeout ( $('#dynScript').attr('src','xxxxxx/banner.php?uname=yyyy&type=2&rows=1'), 3000);
});
</script>