I have used the following function in my javascript code:
function k_addLoadEvent() {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
alert('in');
window.onload = function(){alert('hi');}
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
someFunction();
}
}
}
k_addLoadEvent();
The line window.onload = function(){alert('hi');} is not working in IE 9 and below.
The alert alert('in') is working but not the alert('hi'). I do not see any error in the console.
What am I missing in the code?
Related
I would like to make sure that my image preloads properly, as there's an svg effect, that only looks good when the background is loaded.
function preloader() {
if (document.getElementById) {
document.getElementById("preload-01").style.background = "url(https://i.imgur.com/a9DM6w8.jpg) no-repeat -9999px -9999px";
}
}
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);
https://codepen.io/bonobonobo/pen/WNdWbZq?editors=0100
I have tried this method, yet it seems ineffective.
The above is only a snippet, I have a few other scripts loading as well, and all in all it doesn't do the job.
Is there a mistake in my code?
I have the following in my html
<html>
<body>
<script type="text/javascript">
var hccid=98964571;
function add_chatinline(){
var nt=document.createElement("script");
nt.async=true;
nt.src="http://localhost/ll.js";
var ct=document.getElementsByTagName("script")[0];
ct.parentNode.insertBefore(nt,ct);
console.log("state is ", SORCHAT)//SORCHAT is not defined
}
add_chatinline();
</script>
</body>
</html>
On the ll.js i have
var SORCHAT = SORCHAT || (function () {
return {
init: function (Args) {
console.log("hash is ", Args)
},
};
}());
But now am getting an error of SORCHAT is not defined.
By adding window.onload that is
<script>
window.onload = function(){
SORCHAT.init(12736474676); //this works
}
</script>
But whenever i include another javascript file with window.onload function the SORCHAT.init is not executed.
What am i missing.
You are probably overwriting the window.onload when using it multiple times. You can prevent that with the help of the addEventListener-function.
window.onload = function () {
console.log('onload #1');
}
window.onload = function () { // This replaces the first onload (#1)
console.log('onload #2');
}
window.addEventListener('load', function () {
console.log('onload #A');
});
window.addEventListener('load', function () {
console.log('onload #B');
});
I'm trying to implement clojure in javascript. Can anyone see what the problem is?
var a = (
function()
{
var privateFunction = function()
{
alert('Hello');
}
var OsmanFunction = function()
{
alert('Osman');
}
return
{
publicFunction: function()
{
privateFunction();
}
OsmanFunction: function()
{
OsmanFunction();
}
}})();
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<p> Please hit me</p>
</body>
</html>
You need formatting your code. Really.
var a = (
function () {
var privateFunction = function () {
alert('Hello');
};
var OsmanFunction = function () {
alert('Osman');
};
return {
publicFunction: function() {
privateFunction();
},
OsmanFunction: function() {
OsmanFunction();
}
};
})();
document.getElementById("hitme").addEventListener('click', a.OsmanFunction);
This is working version.
But... in your code:
return
{
You can't transfer return object to the next line.
You have no "," on return object between functions
{
publicFunction: function()
{
privateFunction();
}
OsmanFunction: function()
{
OsmanFunction();
}
}
a is not defined.
Please, in fature be attentive to your code, you make code for an other developers, who will support your project, not for machines.
Your function is returning undefined (returning nothing, which is undefined in js). The lines:
return
{
publicFunction: function()
{
privateFunction();
},
OsmanFunction: function()
{
OsmanFunction();
}
}
Is interpreted as:
return;
{
publicFunction: function()
{
privateFunction();
},
OsmanFunction: function()
{
OsmanFunction();
}
};
Therefore it is equivalent to:
return undefined;
{
publicFunction: function()
{
privateFunction();
},
OsmanFunction: function()
{
OsmanFunction();
}
};
Be very careful with line breaks in javascript. If possible use a coding convention that avoids this kind of mistake. There are several coding conventions that work. Google "Crockford convention" or "standard.js". Either convention work so choose one that you like.
Anyway. I'd suggest you don't start an open brace { in a new line if possible. Get used to starting a brace at the end of the line. It avoids this error.
I think it was just poor formatting, but this is I think what your trying to achieve.
function Test(){
var privateFunction = function(){
alert('Hello');
}
var OsmanFunction = function(){
alert('Osman');
}
return {
publicFunction: privateFunction //NB This is no longer private if you expose it
, OsmanFunction: OsmanFunction
}
};
var tester = Test();
var btn = document.getElementById('hitme');
btn.addEventListener('click', function(e){
e.preventDefault();
tester.OsmanFunction()
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<p> Please hit me</p>
</body>
</html>
Try following code, you missed comma between "publicFunction" and "OsmanFunction" when these returning:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script>
<script>
a = (
function() {
var privateFunction = function() {
alert('Hello');
}
var OsmanFunction = function() {
alert('Osman');
}
return {
publicFunction: function() {
privateFunction();
},
OsmanFunction: function() {
OsmanFunction();
}
}
})();
</script>
</head>
<body>
<p> Please hit me</p>
</body>
</html>
I have some javascript code which detects whether the useragent is an android, iphone or ipod and then only loads my javascript files if this is the case.
The following code works perfectly but I am aware that I do not need to have two 'createscript' functions (with different names) that do the same thing so I am trying to use a parameter/variable instead. I've tried everything i can think of but it's not working.
<script type="text/javascript">
if(navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/webOS/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPod/i)) {
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function createScript()
{
var oNode=document.createElement("script");
document.getElementsByTagName("body")[0].appendChild(oNode);
oNode.setAttribute("id", "newScript", 0);
oNode.setAttribute("type", "text/javascript", 0);
oNode.setAttribute("src", "nav.js", 0);
}
function createScript_()
{
var oNode=document.createElement("script");
document.getElementsByTagName("body")[0].appendChild(oNode);
oNode.setAttribute("id", "newScript", 0);
oNode.setAttribute("type", "text/javascript", 0);
oNode.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js", 0);
}
addLoadEvent(createScript);
addLoadEvent(createScript_);
}
</script>
And here is the new code with parameters that I have been trying out (its the same as above accept I've set a parameter for the createscript function) But it doesnt work:
<script type="text/javascript">
if(navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/webOS/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPod/i)) {
alert("This is a mobile device");
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function createScript(scriptname)
{
var oNode=document.createElement("script");
document.getElementsByTagName("body")[0].appendChild(oNode);
oNode.setAttribute("id", "newScript", 0);
oNode.setAttribute("type", "text/javascript", 0);
oNode.setAttribute("src", + scriptname + , 0);
}
createscriptlibrary = createScript("https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js");
createmyscript = createScript("nav.js");
addLoadEvent(createscriptlibrary);
addLoadEvent(createmyscript);
}
</script>
It's probably something small but I can't figure it out. Thanks for your help.
Edit:
Thanks to #t-j-crowder I have edited my code as follows and this works perfect:
<script type="text/javascript">
if(navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/webOS/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPod/i)) {
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function createscript(scriptName) {
var oNode = document.createElement('script');
oNode.src = scriptName;
document.body.appendChild(oNode);
}
addLoadEvent(createscript.bind(undefined, "https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"));
addLoadEvent(createscript.bind(undefined, "nav.js"));
}
</script>
There are still some issues with this code as #t-j-crowder pointed out about the fact that I cannot rely on my two .js files loading in the right order so I will try out the guard as he suggested below in his answer. Thanks for all the comments.
New edit to question-loading in a css file:
I now have the following code which loads my jquery lib and nav2.js file when the page is loaded. This works perfect. I am trying to get my code to load a css file dynamically when the browser supports javascript but it is not working. Can anybody see why? is it because the page is displaying before the css file is loaded? Here is my script code:
<script type="text/javascript">
function loadcssfile(filename){
var fileref=document.createElement("link");
fileref.href = filename;
document.getElementsByTagName("head")[0].appendChild(fileref);
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function createscript(scriptName) {
var oNode = document.createElement('script');
oNode.src = scriptName;
document.body.appendChild(oNode);
}
addLoadEvent(createscript.bind(undefined, "https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"));
addLoadEvent(createscript.bind(undefined, "nav2.js"));
loadcssfile("jqueryjava.css");
</script>
The reason that doesn't work is that createScript doesn't return a function, but you're expecting it to.
The simplest way is just to do this:
addLoadEvent(function() { createscript("https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"); });
addLoadEvent(function() { createScript("nav.js"); });
Note, though, that you're giving the same id value to each script tag created by createScript, which isn't valid.
In an ES5-enabled environment, you could use Function#bind, but something about your question suggests to me you can't rely on being in an ES5-enabled environment. But for completeness:
addLoadEvent(createscript.bind(undefined, "https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"));
addLoadEvent(createScript.bind(undefined, "nav.js"));
Actually, no, the simplest way is to use any of several libraries designed for this, like RequireJS. :-)
Side note: Your createScript function can be markedly simpler (and in fact, the one you've quoted in your question has a syntax error as of the + before scriptName):
function createScript(scriptName) {
var oNode = document.createElement('script');
oNode.src = scriptName;
document.body.appendChild(oNode);
}
There's no need to set type, and you don't want to set id unless you're also passing in an id for each script. And both src and type are reflected properties, no need to use setAttribute on them.
And a final side note: Your nav.js cannot rely on jQuery already being loaded if you load the scripts this way. nav.js can be retrieved and evaluated (run) before jQuery is, even though you're creating the jQuery script element first. Scripts added dynamically are not necessarily evaluated in order. So you need a guard on your nav.js code, like:
(function() {
check();
function check() {
if (typeof jQuery === "undefined") {
setTimeout(check, 50);
}
else {
init();
}
}
function init() {
}
})();
That will check for jQuery and wait 50ms if it doesn't find it (and keep doing that forever, you might want a master timeout).
In my latest edit above I was wondering how to add a css file dynamically.
I have used the following code instead and it is now working. Thanks
<script type="text/javascript">
var headID = document.getElementsByTagName("head")[0];
var cssNode = document.createElement('link');
cssNode.type = 'text/css';
cssNode.rel = 'stylesheet';
cssNode.href = 'jqueryjava.css';
headID.appendChild(cssNode);
</script>
Before i ask this question, i never post about questions like this but I don't understand how to implement it in my code. i have code like this
window.onload = function() {
var url = getQueryVariable("url");
document.getElementById('view').src = url;
}
window.onload = function() {
var linkDirect = document.getElementsByClassName("frame");
for (var i = 0; i < linkDirect.length; i++) {
linkDirect[i].href = "http://namablog.blogspot.com/p/demo.html?url=" + linkDirect[i].href
}
}
then, how can I make the code execution using only one window.onload
You can use addEventListener or any jQuery equivalent.
window.addEventListener('load', function (){
alert('Function #1');
});
window.addEventListener('load', function (){
alert('Function #2');
});
Be sure to call these before the window is loaded.
window.addEventListener will not work in IE so use window.attachEvent
You can do something like this
function fun1(){
// do something
}
function fun2(){
// do something
}
var addFunctionOnWindowLoad = function(callback){
if(window.addEventListener){
window.addEventListener('load',callback,false);
}else{
window.attachEvent('onload',callback);
}
}
addFunctionOnWindowLoad(fun1);
addFunctionOnWindowLoad(fun2);
Just my 2 cents, My personal fav way of doing this is as follows:
function window_onload(cb) {
try {
if (typeof cb == 'function') {
if (document.readyState == 'complete') cb();
else if (window.hasOwnProperty('jQuery')) jQuery(window).on('load', cb);
else if (window['addEventListener']) document.addEventListener('load', cb, false);
else if (window['attachEvent']) {
// iFrame
if (window['frameElement']) document.attachEvent('onreadystatechange', function(){ if (document.readyState === 'complete') window_onload(cb); });
else window.attachEvent('onload', cb);
}
else {
var fn = window.onload; // very old browser, copy old onload
window.onload = function() { fn && fn(); ready(); };
}
}
}
catch (err) { if (window['console'] && console['error']) console.error("ERROR[window_onload()]", err); }
return window;
}
This pretty much covers just about everything. What little (mainly extremely old browsers I suppose?) it doesn't cover, you could easily debug, if needed. This also goes ahead and launches the callback if the document is already 'loaded'.
The simplest solution that has worked for me:
function doOnLoad() {
onloadfn1();
onloadfn2();
onloadfn3();
}
window.onload = doOnLoad;
This article has explained it in details: http://developer.expressionz.in/blogs/2009/03/07/calling-multiple-windows-onload-functions-in-javascript/
I hope this helps some of you.