skip function if missing script - javascript

I am building within a content management system, so I have to get creative with load functions.
I have 2 scripts running on load. A random background image for the home page, and the navigation menu. I included both in a separate script that runs on load. The only page to get the background image is the home page. So on all the other pages that do not have the random home script linked, the script errors out and the menu does not load.
I would like the background image to execute first. A bad work around is to load the menu first, and let the random home script break on any sub pages but this is NOT ideal and I am hoping to find a solution.
I would like to load the image first, and then run the navigation script. And in the event that the image script is undefined, I would like it to skip, and execute the navigation script.
Here is my code:
function start() {
var randH = randomHome();
var undefined = false;
if (randH === undefined) {
loadNAV();
}
else {
randomHome();
loadNAV();
}
}
window.onload = start;
The 2 functions are linked in separate files and work just fine when listed like this:
function start() {
loadNAV();
randomHome();
}
window.onload = start;
But this leaves errors on sub pages that do not get the background image. So i am searching for a no error answer that loads the background image first, or skips it, and then the navigation.

Create an anonymous function that runs on load and checks for the existence of the start() function. If it exists, call it.
window.onload = function() {
if (start) {
start();
}
};
Remove the undefined = false line. undefined is a reserved keyword and already evaluates as "falsy" and what you've done will cause a lot of issues for anything else relying on the undefined keyword. Instead, change the if statement to use == instead of ===. == evaluates equality, === evaluates identity.
If you're trying to prevent the randomHome() script from running if it doesn't exist, the same code would be used inside the start() function.
function start() {
// only call randomHome function if it exists
if (randomHome) {
var home = randomHome();
// anything else to do with the homes goes here
}
// load the nav regardless of whether randomHome exists
loadNAV();
}

This is what ended up working. thanks all.
function start() {
if(window.randomHome == undefined )
{
loadNAV();
}
else {
randomHome();
loadNAV();
}
}
window.onload = start;

Related

How to dynamic load Jquery inside a JavaScript Class constructor and proceed the execution only after jquery has been fully loaded

This is actually a merge of three differents questions already all well answered here on stack overflow !
1 - How to Dynamic Load a JavaScript file from inside a Js Script :
2 - How to Dynamic Load Jquery
3 - SetTimeout inside a JS Class using this
Basically, I am building a class that will inject some pages inside my clients's website.
To do so, the client just need to add my script src on the page.
<script src="<my_pub_http_address>/MyClass.js">
Once the script is invoked, I will need jquery to continue the execution !
But, I cannot know if the website that invoked the scripts has jquery already loaded.
So, I need to check if jquery is loaded, if not, I will have to load it, append to head and only then when jquery is loaded and working, I will proceed with the script's execution .
PS: this is a kind of legacy answer ! I already had the solution beforehand !
So, any improvement will be appreciated !
That's the solution I've found:
// MyClass.js
var counterLoopLoad = 0;
class MyClass {
constructor(){
// do the code that does not need jQuery
return this.Init()
}
JqueryLoader() {
// Loop Breaker
counterLoopLoad ++;
if (counterLoopLoad == 100) {
throw 'I need jQuery in order to do what I am suppose to do!';
}
var __jquery = document.createElement('script');
__jquery.src = "http://code.jquery.com/jquery-latest.min.js";
__jquery.type = 'text/javascript';
// if needed ....
// __jquery.onload = function() {
// some code here
//
// };
// must be prepend !!! append won't work !!!!
document.head.prepend(__jquery);
// here is the point that makes all work !!!!
// without setTimeOut, the script will get in a loop !
var that = this;
setTimeout(function () {
that.Init();
}, 500);
}
Init() {
if (typeof jQuery == 'undefined') {
return this.JqueryLoader();
}
jQuery.ajax(...);
}
}

Processing.js doesn't allow external javascript bind in firefox

I'm trying to send data to a processing script. But for some reason the variable pjs below binds to the canvas "competence1" and enters the first if statement, but then the bindJavascript(this)-call returns error, but only in firefox. (works perfectly in chrome):
[pjs.bindJavascript is not a function]
var bound = false;
function initProcessing(){
var pjs = Processing.getInstanceById('competence1');
if (pjs != null) {
// Calling the processing code method
pjs.bindJavascript(this);
bound = true;
//Do some work
}
if(!bound) setTimeout(initProcessing, 250);
}
Environment: Mac OS X - Lion;
OBS! The bindJavascript(this)- method exists in the pde script loaded in the canvas-tag
By wrapping up all my script in a varable-map and by using the second way for setTimeout to be called i can follow each state and control the result.
So wrap it up-->
var ex = {
init : function(canId){
var canId = canId;
// check the if bound
// bind in this closure
// set new timer
}
}
setTimeout-->
setTimeout('ex.init("'+canId+'")', 2000);
and ofcourse add the parameter in so it can hold that value during it's own execution. So processing works just fine and i should use closure more often, that's the solution.
I had the same problem. I was using almost identical JS to you (which I got from the Pomax tutorial), and it was working fine. However, when I added the following preload directive (to load a backdrop), then suddenly my initProcessing function stopped working.
/* #pjs preload="metal_background.jpg"; */
The error message was the same: pjs.bindJavascript is not a function
On debugging, I could see that the pjs object did indeed not have a bindJavaScript function exposed, even though there is one declared in my PDE file.
It turns out this was purely down to timing... the preload had slowed down the initialisation of the processing object, so the second time round the 250ms loop, the pjs object existed, but didn't yet have its bindJavaScript function.
I am not 100% sure how Processing.js does this object construction, but in this case, a simple solution was just to check whether bindJavaScript actually was defined! I changed my code to the following:
var bound = false;
function initProcessing() {
var pjs = Processing.getInstanceById('mySketchId');
if(pjs != null) {
if(typeof(pjs.bindJavaScript) == "function") {
pjs.bindJavaScript(this);
bound = true;
}
}
if(!bound) setTimeout(initProcessing, 250);
}
After this it worked fine!

How to make my function to be page specific or div id specific?

I am writing javascript to my web pages, but there is a number of functions and loops, that i think are running in all pages, so the first one is running and failing on the second page. Because of this, the javascript function on the second page is not running.
Can anyone give me an idea of how to create page-specific functions or check the availability of an id? I don't use any frameworks.
thanks in advance.
my javascript code is :
window.onload = function(){
var yellows = document.getElementById('magazine-brief').getElementsByTagName('h2');
var signUp = document.getElementById('signup-link');
function animeYellowBar(num){
setTimeout(function(){
yellows[num].style.left = "0";
if(num == yellows.length-1){
setTimeout(function(){
signUp.style.webkitTransform = "scale(1)";
},num * 250);
}
}, num * 500);
}
for (var i = 0; i < yellows.length; i++){
animeYellowBar(i);
}
alert("alert second page");
}
in this code, the alert message not working on second page. any idea?
If I understand you correctly, you have a javascript function, that you want to attach to an event from a specific div element in your page.
a) Include an event directly to you HTML page, something like this:
<div id="element" onclick="some_function();">Text is here</div>
b) Use a javascript function (add this code between <script> tag):
window.onload = function() {
document.getElementById("element").setAttribute("onclick", "some_function()")
}
The best way would be to only include those scripts on the pages which need them. Why waste time loading and parsing scripts you don't need?
If you must keep them on every page, put your functions in an if statement and check for something unique to the page that needs them (such as a form element or field ID).
Update
In response to your comment:
You have to code more defensively. You are attempting to make use of the magazine-brief and signup-link elements before you have made certain that they exist. Never trust that the proper element was returned - always check that it was before attempting to use that element.
I suggest checking your vars like so:
var yellows = document.getElementById('magazine-brief').getElementsByTagName('h2');
var signUp = document.getElementById('signup-link');
if (yellows != 'undefined' && signUp != undefined)
{
function animeYellowBar(num)
{
//...
}
}

Windows 7 Gadget Flyout Question

I'm having troubles with my flyout. What happens with my gadget is you double click a component and it will have a corresponding flyout window. If you double click that or any other visual component with a flyout, though, the flyout document is returned as null. I have no idea why this is, and if you make the flyout go away and reopen it or a new one it's ok. It's only when a flyout is already opened this happens. I'm looking for some ideas on why this is.
Double click code:
Blah.prototype.ondblclick = function()
{
var me = this.parent;
if (System.Gadget.Flyout.show)
{
// flyout is already shown, make sure it shows our stuff
System.Gadget.Flyout.file = FLYOUT_FILE;
onFlyoutShow();
}
else
{
System.Gadget.Flyout.file = FLYOUT_FILE;
System.Gadget.Flyout.onShow = onFlyoutShow;
System.Gadget.Flyout.show = true;
}
System.Gadget.Flyout.onHide = onFlyoutHide;
function onFlyoutShow()
{
me.flyoutOpen = true;
me.updateFlyout();
}
function onFlyoutHide()
{
me.flyoutOpen = false;
}
};
Executed code:
Blah.prototype.updateFlyout = function ()
{
var flyoutDoc = System.Gadget.Flyout.document;
//flyoutDoc is null at this point
var info = flyoutDoc.getElementById("info");
info.innerHTML = "info: " + this.information;
//Error thrown: 'null' is null or not an object
}
I don't know a lot about writing gadgets for windows 7, but to me it looks a lot like a timing issue. When the flyout is already there, you change the file property which tells it to load a new file. Without waiting you then call onFlyoutShow which tries to get the document and the document isn't loaded yet.
My first thought is: Doesn't the onShow event fire when you set the file? Probably doesn't or you wouldn't have the if, but worth verifying.
If that doesn't work, calling onFlyoutShow in a timeout. Start with a long timer, like 1000. And then shorten it, hopefully you can get down to 0: setTimeout(onFlyoutShow, 0);

Javascript,calling child window function from opener doesn't work

I'm developing a web application that opens a popup using windows.open(..). I need to call a function on the opened window using the handle returned by "window.open", but I'm always getting the error message "addWindow.getMaskElements is not a function", as if it couldn't access the function declared on child window. This is the behavior in both IE and FF. My code looks like this:
function AddEmail(target,category)
{
if(addWindow == null)
{
currentCategory = category;
var left = getDialogPos(400,220)[0];
var top = getDialogPos(400,220)[1];
addWindow = window.open("adicionar_email.htm",null,"height=220px, width=400px, status=no, resizable=no");
addWindow.moveTo(left,top);
addWindow.getMaskElements ();
}
}
I've googled and read from different reliable sources and apparently this is supposed to work, however it doesn't.
One more thing, the functions in child window are declared in a separate .js file that is included in the adicionar_email.htm file. Does this make a difference? It shouldn't..
So, if anyone has ran into a similar problem, or has any idea of what I'm doing wrong, please, reply to this message.
Thanks in advance.
Kenia
The window creation is not a blocking operation; the script continues to execute while that window is opening and loading the HTML & javascript and parsing it.
If you were to add a link on your original page like this:
Test
You'd see it works. (I tried it just to be sure.)
**EDIT **
Someone else posted a workaround by calling an onload in the target document, here's another approach:
function AddEmail()
{
if(addWindow == null) {
addWindow = window.open("test2.html",null,"height=220px, width=400px, status=no, resizable=no");
}
if(!addWindow.myRemoteFunction) {
setTimeout(AddEmail,1000);
} else { addWindow.myRemoteFunction(); }
}
This keeps trying to call addWindow.myRemoteFunction every 1 second til it manages to sucessfully call it.
The problem is that window.open returns fairly quickly, the document that is requested and then any other items that that document may subsequently refer to will not yet have been loaded into the window.
Hence attempting to call this method so early will fail. You should attach a function to the opened window's load event and attempt to make you calls from that function.
The problem with the below one is :
When the javascript is being executed in the parent window, the child window is not loading. Hence, the invoking function from parent window is in the infinite loop and it is leading to crashing the window.
The window creation is not a blocking operation; the script continues
to execute while that window is opening and loading the HTML &
javascript and parsing it.
If you were to add a link on your original page like this:
Test
You'd see it works. (I tried it just to be sure.)
**EDIT **
Someone else posted a workaround by calling an onload in the target
document, here's another approach:
function AddEmail()
{
if(addWindow == null) {
addWindow = window.open("test2.html",null,"height=220px, width=400px, status=no, resizable=no");
}
if(!addWindow.myRemoteFunction) {
setTimeout(AddEmail,1000);
} else { addWindow.myRemoteFunction(); }
}
This keeps trying to call addWindow.myRemoteFunction every 1 second
til it manages to sucessfully call it.
You are calling the function immediately after opening the window; the page on the popup may not be loaded yet, so the function may not be defined at that point.

Categories