JavaScript function not called on page load - javascript

I have a JavaScript function placed at the bottom of my page but for some reason the page isn't called on page load. I tried running it on console to be sure it doesn't produce an error, but it ran perfectly fine. I even tried setting the
window.onload = function() {applyMovement();}
That didn't even work.
about.js
function applyMovement() {
let bars = document.getElementsByClassName('progress-bar');
for (let i = 0; i < bars.length; i++) {
moveBar(bars[i], i);
}
}
index.blade.php
...
</body>
<script src="{{ asset('/js/about.js') }}">window.onload = function() {applyMovement();} </script>
</html>
It should be noted that I am using Laravel 5.8. I've placed my JS file inside the public directory. Also other actions on the file are being ran but not this patricular function.

Try placing a new script tag under the declaration of about.js. Like so:
...
</body>
<script src="{{ asset('/js/about.js') }}"> </script>
<script> window.onload = function() {applyMovement();} </script>
</html>
If that didnt work, try the following (bind it to window as a global):
window.applyMovement = function() {
let bars = document.getElementsByClassName('progress-bar');
for (let i = 0; i < bars.length; i++) {
moveBar(bars[i], i);
}
}

Related

Javascript: Error in custom script for lazyload images

I am trying to write the following script to lazyload background images of sub-menu on a website. But this function returns the error
Missing ) after argument list
My requirement is to load the background images after the window loaded completely. What i am doing is , I have added some data attributes to get the background image url, position etc. and then on windows load call this function which adds the css for the sub-menu.
<script>
function menuImageLazyLoad() {
var imgDefer = document.getElementsByClassName('megamenu-content');
for (var i = 0; i < imgDefer.length; i++) {
if(imgDefer[i].getAttribute('data-background-image')) {
imgDefer[i].css(
"background-image":+imgDefer[i].getAttribute('data-background-image'),
"background-position":+imgDefer[i].getAttribute('data-background-position'),
"background-repeat":+imgDefer[i].getAttribute('data-background-repeat')
);
console.log(imgDefer[i].getAttribute('data-background-image'));
}
}
}
window.onload = menuImageLazyLoad;
</script>
console logs returns the url of image:
url(image/sub_menu_image.jpg)
How can i fix this problem?
Update:
This is the final solution for my problem. I hope it may help someone
<script>
function menuImageLazyLoad() {
var imgDefer = document.getElementsByClassName('megamenu-content');
for (var i = 0; i < imgDefer.length; i++) {
if(imgDefer[i].getAttribute('data-background-image')) {
$(imgDefer[i]).css("background-image",imgDefer[i].getAttribute('data-background-image'));
$(imgDefer[i]).css("background-position",imgDefer[i].getAttribute('data-background-position'));
$(imgDefer[i]).css("background-repeat",imgDefer[i].getAttribute('data-background-repeat'));
}
}
}
window.onload = menuImageLazyLoad;
</script>
I guess you miss {}
For multiple attribute css settings,
It should be set as an object https://www.w3schools.com/jquery/jquery_css.asp
imgDefer[i].css(
{"background-image":+imgDefer[i].getAttribute('data-background-image'),
"background-position":+imgDefer[i].getAttribute('data-background-position'),
"background-repeat":+imgDefer[i].getAttribute('data-background-repeat')
});

2 functions init inside one JS

I try to combine 2 defer functions init to 1 Java script.
I actually try now combine another one but he make conflict and the JS very heavy. this is 2 different script + 1 is not so important (but if you guys succeed help me combine all of them perfectly is be better).
This the code I try put after I edit him 2( 2 functions init ):
function init() {
var imgDefer = document.querySelectorAll('div[data-src]');
var style = "background-image: url({url})";
for (var i = 0; i < imgDefer.length; i++) {
imgDefer[i].setAttribute('style', style.replace("{url}", imgDefer[i].getAttribute('data-src')));
}
imgDefer = document.getElementsByTagName('img');
for (var i = 0; i < imgDefer.length; i++) {
if (imgDefer[i].getAttribute('data-src')) {
imgDefer[i].setAttribute('src', imgDefer[i].getAttribute('data-src'));
}
}
}
window.onload = init;
I make him a short too... he defers the images but slower the site:
function init(){for(var t=document.querySelectorAll("div[data-src]"),e=0;e<t.length;e++)t[e].setAttribute("style","background-image: url({url})".replace("{url}",t[e].getAttribute("data-src")));t=document.getElementsByTagName("img");for(e=0;e<t.length;e++)t[e].getAttribute("data-src")&&t[e].setAttribute("src",t[e].getAttribute("data-src"))}window.onload=init;
(you can look the code is deferred on the website: locksmithunit.com)
but he very slow on the page load.
and this all the original codes... these codes are for deferring images
and the last one is for "frame"
the frame not so important. and if you can give me him separately because
have pages I don't have iframe.
please help me guys, i very lost.
I most combine at least the first 2 scripts from all the 3 I send now:
<script>
function init() {
var imgDefer = document.getElementsByTagName('img');
for (var i=0; i<imgDefer.length; i++) {
if(imgDefer[i].getAttribute('data-src')) {
imgDefer[i].setAttribute('src',imgDefer[i].getAttribute('data-src'));
} } }
window.onload = init;
<script>
<script>
function init() {
var imgDefer = document.querySelectorAll('div[data-src]');
var style = "background-image: url({url})";
for (var i = 0; i < imgDefer.length; i++) {
imgDefer[i].setAttribute('style', style.replace("{url}", imgDefer[i].getAttribute('data-src')));
}
}
window.onload = init;
</script>
<script>
function init() {
var vidDefer = document.getElementsByTagName('iframe');
for (var i=0; i<vidDefer.length; i++) {
if(vidDefer[i].getAttribute('data-src')) {
vidDefer[i].setAttribute('src',vidDefer[i].getAttribute('data-src'));
} } }
window.onload = init;
</script>
ok. so I try to defer images on my website... on 120 pages...
now, when i start, i was able to defer only images.
after that, I succeed defer the background-image: url().
but it is different JS as you see on the example I post before.
I succeed combine them but still, the JS no give full power.
after that, I start to fix again pages and i notice have google maps iframe
in couple of pages. ( something like 40 pages).
and I try to defer the iframe as well but it was too much for the javascript and the website loses the page load...
the JS needs to rewriting again...
i try a couple of variations as I post before, but none of them really improve the page load.
if we sucssed fix the Javascript at least put the 2 functions inside JS, JS of the background and images you will save me because I already edit all the 120 pages and the JS work and defer, but damage the page load because the JS is not written well.
(iframe is not so important like the images and the background)

Problem with local progress bar code while it works properly on CodePen? [duplicate]

I'm trying to run a simple few lines of code using an index.html file and a script.js file, nothing else.
In the HTML file, I have doctype html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="javascript/script.js"></script>
</head>
<body>
<div id="content1">This is content 1 </div>
<div id="content2">This is content 2 </div>
<div id="content3">This is content 3 </div>
</body>
</html>
And for my javascript section i have:
var elems = $("div");
if (elems.length) {
var keep = Math.floor(Math.random() * elems.length);
for (var i = 0; i < elems.length; ++i) {
if (i !== keep) {
$(elems[i]).hide();
}
}
}
When I run this in CodePen, or even on the code editor on this website, it works fine. But it doesn't work when I use the files on my desktop (index.html, script.js I do believe the folder structure is correct (script.js is in the javascript folder.)
Thank you all
Move your script tag just before the closing of the body tag:
<script src="javascript/script.js"></script>
</body>
This way the DOM will be available when your script runs.
If you prefer to keep your script in the head part, then wrap your code in a DOMContentLoaded event handler:
document.addEventListener("DOMContentLoaded", function() {
var elems = $("div");
if (elems.length) {
var keep = Math.floor(Math.random() * elems.length);
for (var i = 0; i < elems.length; ++i) {
if (i !== keep) {
$(elems[i]).hide();
}
}
}
});
... so to have your code run when the DOM is ready.
You did not tag your question with jquery, but as you seem to use it, you can use this shorter code for doing essentially the same as above:
$(function() {
var $elems = $("div").hide(),
$elems.eq(Math.floor(Math.random() * $elems.length)).show();
});
wrap your code in this function to execute it if the document is ready.
$(document).ready(function (){
// your code goes here
});

Render blocking by jquery and bootstrap library

I have index.html file where I have Jquery library and bootstrap library for js being loaded in <head> tag, they are reported as the reason for render blocking, where, jquery.min.js takes 932 ms and bootstrap.min.js takes 765 ms to load. Here, I decided to load the jquery and boostrap files after loading the page following this article. But since I had other dependent JS files as well, I decided to create a Javascript array and iterate it to create the dynamic script tags. Which is doing its part, but the page doesnt load because other dependent files doesnt find the jquery file.
I believe this is happening because, before jquery.min.js gets loaded completely other files gets loaded and hence it breaks.
Note: since all the js files are from the codebase, It doesnt make sense to use defer or async.
Below is the code I am using in the bottom of the page before </body> tag.
<script type="text/javascript">
var source = [
"common/scripts/external/jquery-3.2.1.min.js",
"common/scripts/external/bootstrap.min.js",
"common/scripts/other/utility.min.js?v=1.0.0",
"common/scripts/external/jquery.ui.widget.min.js",
"common/scripts/external/jquery.fileupload.min.js",
"common/scripts/external/jquery.fileupload-process.min.js",
"common/scripts/external/jquery.fileupload-validate.min.js",
"common/scripts/external/jquery.knob.min.js",
"common/scripts/external/jquery.payform.min.js"
]
function downloadJSAtOnload(source) {
for (var i = 0; i < source.length; i++) {
var element = document.createElement("script");
element.src = source[i];
document.body.appendChild(element);
}
}
if (window.addEventListener) {
window.addEventListener("load", downloadJSAtOnload(source), false);
} else if (window.attachEvent) {
window.attachEvent("onload", downloadJSAtOnload(source));
} else {
window.onload = downloadJSAtOnload(source);
}
</script>
The errors when I load the page:
Please suggest whats the right way to solve the render blocking and if this is the right direction, how I can allow Jquery to load first before every other files get loaded
you should add jquery before this js script:
<script src='common/scripts/external/jquery-3.2.1.min.js' async></script>
<script src='common/scripts/external/jquery.ui.widget.min.js' async></script>
<script src='common/scripts/external/jquery.fileupload.min.js' async></script>
<script src='common/scripts/external/jquery.fileupload-process.min.js' async></script>
<script src='common/scripts/external/jquery.fileupload-validate.min.js' async></script>
<script src='common/scripts/external/jquery.knob.min.js' async></script>
<script src='common/scripts/external/jquery.payform.min.js' async></script>
<script type="text/javascript">
var source = [
"common/scripts/external/bootstrap.min.js",
"common/scripts/other/utility.min.js?v=1.0.0"
]
function downloadJSAtOnload(source) {
for (var i = 0; i < source.length; i++) {
var element = document.createElement("script");
element.src = source[i];
document.body.appendChild(element);
}
}
if (window.addEventListener) {
window.addEventListener("load", downloadJSAtOnload(source), false);
} else if (window.attachEvent) {
window.attachEvent("onload", downloadJSAtOnload(source));
} else {
window.onload = downloadJSAtOnload(source);
}
</script>
I think you should call bootstrap before this script too. check and see if it did not work correctly move the bootstrap.js before the script, too.

Code works in Codepen, but not with my desktop files

I'm trying to run a simple few lines of code using an index.html file and a script.js file, nothing else.
In the HTML file, I have doctype html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="javascript/script.js"></script>
</head>
<body>
<div id="content1">This is content 1 </div>
<div id="content2">This is content 2 </div>
<div id="content3">This is content 3 </div>
</body>
</html>
And for my javascript section i have:
var elems = $("div");
if (elems.length) {
var keep = Math.floor(Math.random() * elems.length);
for (var i = 0; i < elems.length; ++i) {
if (i !== keep) {
$(elems[i]).hide();
}
}
}
When I run this in CodePen, or even on the code editor on this website, it works fine. But it doesn't work when I use the files on my desktop (index.html, script.js I do believe the folder structure is correct (script.js is in the javascript folder.)
Thank you all
Move your script tag just before the closing of the body tag:
<script src="javascript/script.js"></script>
</body>
This way the DOM will be available when your script runs.
If you prefer to keep your script in the head part, then wrap your code in a DOMContentLoaded event handler:
document.addEventListener("DOMContentLoaded", function() {
var elems = $("div");
if (elems.length) {
var keep = Math.floor(Math.random() * elems.length);
for (var i = 0; i < elems.length; ++i) {
if (i !== keep) {
$(elems[i]).hide();
}
}
}
});
... so to have your code run when the DOM is ready.
You did not tag your question with jquery, but as you seem to use it, you can use this shorter code for doing essentially the same as above:
$(function() {
var $elems = $("div").hide(),
$elems.eq(Math.floor(Math.random() * $elems.length)).show();
});
wrap your code in this function to execute it if the document is ready.
$(document).ready(function (){
// your code goes here
});

Categories

Resources