should preloader be inside DOMContentLoaded or load event - javascript

I want to add a preloader to my website untill the website is fully loaded images, js, fonts everything but I'm confused which should I use
window.addEventListener('DOMContentLoaded', () => {
// code
});
or
window.addEventListener('load', () => {
// code
});
And if I used load or DOMContentLoaded should I stop using defer for my script files?
And also if I have imported modules should it be outside the event? For example:
import { gsap } from "gsap";
window.addEventListener('DOMContentLoaded', () => {
// code
});

I use this preloader code for my website. You can check this.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id="preloader" style="position: fixed; left: 0; top: 0; z-index: 999; width:
100%; height: 100%; overflow: visible; background: #333 url('pre_loading.gif') no-
repeat center center;"></div>
<div id="container" style="display:none;">your page content here</div>
<script>
$(window).load(function(){
$('#preloader').fadeOut('slow',function(){$(this).remove();});
$('#container').show();
});
</script>
</body>
</html>

You can hide the preloader when the event you choose is triggered.
defer attribute
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.
The DOMContentLoaded event will fire as soon as the DOM hierarchy has been fully constructed, the load event will do it when all the images and sub-frames have finished loading.
You could also read the documentation...
https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script

Related

Variable scope in javascript - not being picked up by event listener

I have a question that started as a practical one as I want an element containing a video collapsing when the video finishes, for which I need to add an event listener, but as it wasn't working I started doing some testing and I don't understand how is JavaScript accessing variables.
Ok, so in my project I have a video inside an iframe, like so:
html
<p> ...some tex...
<span id="clickable" class="link">click me to watch video</span>.<span><iframe id="frame" class="rect" src="iframe.html" scrolling="no" marginwidth=0 marginheight=0></iframe></span>
...some more tex...</p>
the iframe just has a video
iframe:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="script2.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<video id="myVid" width="350" height="200" >
<source src="someVideo.mp4" type="video/mp4">
</video>
</body>
</html>
the JavaScript is like so:
$(document).ready(function(){
$("#clickable").click(function(){
var rect = $(this).next().find('.rect');
if (rect.hasClass( "open" )){
rect.removeClass("open");
rect.contents().find("#myVid").get(0).pause();
} else {
rect.addClass("open");
rect.contents().find("#myVid").get(0).play();
}
});
and the css
.rect{
float: left;
height: 0px;
width: 350px;
display: block;
margin: 0px;
padding: 0px;
opacity: 0;
transition-property: all;
transition-duration: 2s;
transition-timing-function: ease-in-out;
}
.open {
height: 200px;
width: 350px;
opacity: 1;
padding-bottom: 10px;
padding-top: 10px;
}
Ok so this works. When i click the link "clickable" the javascript adds the class "open" to the the iframe which makes the height go from 0 to 200px and so the video slides open. Then when i click again the video closes.
So what I was trying to do is to add a function that would also close the video when the video finishes with this function:
$('#myVid').on('ended',function(){
rect.removeClass("open");
alert('finished');
});
And here is when the problem starts. The question is where to place this function. If I place it outside "clickable" the function, it does get triggered when the video finishes (the alert box shows up), but the video doesn't collapse, so I concluded that it couldn't reach the video. Then I modified the event listener like so:
$('#rickieVid').on('ended',function(){
if ($(rect).hasClass("open")){alert('has class')}
else {alert('has not');}
});
And the alert box shows: "has not". So this really confuses me as the class "open" was clearly added with the "clickable" event. Can someone help me understand why this is not working? Many thanks
P
===================================edit==================================
I perhaps should mention that I did try to put the "rect" variable outside the "clickable" function to make it global, like so:
$(document).ready(function(){
var rect;
$("#rickie").click(function(){
rect = $(this).next().find('.rect');
etc...
And then modifying my function to access the global variable like so:
$('#rickieVid').on('ended',function(){
if (rect.hasClass("open")){alert('has class')}
else {alert('has not');}
});
Which still doesn't work as it comes with this error:
TypeError: undefined is not an object (evaluating 'rect.hasClass')
You can achieve this by attaching the load event handler to the iframe jquery object as the main document is ready even if the iframe source is loading in it and also sometimes the video control takes time to load as well.
Anyway, In that event, you need to set the global player object and also attach the ended event handler to the player.
jQuery code to use:
$(document).ready(function(){
var frame = $("#frame");
var player;
frame.bind("load", function () {
player = $(this).contents().find("#myVid");
player.on('ended', function () {
frame.removeClass("open");
alert('finished');
});
});
$("#clickable").click(function(){
if (frame.hasClass("open"))
{
frame.removeClass("open");
player[0].pause();
}
else {
frame.addClass("open");
player[0].play();
}
});
});
One thing to note here. If the iframe source is a cross domain url then the .contents() will throw a security error. This only works if the iframe source page is within the same domain.

JavaScript erratic with starting point funciton

fairly new to js. I have a simple project in which all I have is an image twice the height of the screen. I want the webpage to open at the bottom of the page, so I have added the "window.scroll" funtion method in javascript. This works fine... most of the time. Sometimes, particularly if I test on a mobile device with a home server, the javascript just doesn't fire up and the page starts at the top. So my main question is: is there a way to do the same as "window.scroll" but with CSS, bypassing js altogether? And a second question I would have is, why is javascript so flaky? I am really new to web development and I have already twice (the other time with the "slide" method) had to use css instead of js because js doesn't work properly, or it needs to be cached etc... is this normal behaivour or just me really bad at writing it at this point? Thanks for your time. P
Here's the simple code:
$(document).ready(function(){
window.scroll(0,2000);
});
body {
margin: 0px;
padding: 0px;
}
img {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<img src="https://pixabay.com/static/uploads/photo/2016/10/18/21/22/california-1751455_960_720.jpg" width="100%" style="display: block;">
</body>
</html>
CSS:
body {
margin: 0px;
padding: 0px;
}
img {
width: 100%;
}
JavaScript:
$(document).ready(function(){
window.scroll(0,2000);
});
I think the problem is that the image takes time to load.So I think your event is fired however the image loads later and changes the page size again. The load event will fire after images are loaded.
try this code instead:
$(window).on("load", ,function(){
window.scroll(0,2000);
});

Why isn't my web page transition working? (HTML, CSS, JavaScript)

Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<link href="index.css" rel="stylesheet" type="text/css">
<script src="main.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<a id="myLink" href="#">
Click to slide in new page
</a>
<iframe id="newPage" src="http://jsfiddle.net"></iframe>
</body>
</html>
And here is my CSS:
#myLink {
position: absolute;
}
iframe {
width: 100%;
height: 100%;
top: 100%;
position: fixed;
background-color: blue;
}
And my JavaScript:
$("#myLink").click(function () {
$('#newPage').transition({top: '0%' });
});
I am literally copy and pasting from this source http://jsfiddle.net/TheGAFF/hNYMr/ to achieve a transition between web pages using iframe but for some reason when I try this simple code in my browser, it doesn't work. I can't see why this doesn't work in my browser when I link it to index.html. Can anyone help? Thanks.
Edit: The "#myLink" in the CSS page isn't commented out, it just happened to format like this in the question.
Look in your JavaScript console. Expect to see an error about $ not being defined.
See this code:
<script src="main.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
First you load your script, which tries to use $. Then you try to load jQuery, which defines $.
Swap the order or your script elements.
You then have a second problem.
$("#myLink")
You have no element with id="myLink" in the document at the time the script runs.
It doesn't get added to the DOM until 4 lines later.
Either:
move the script so it appears after the elements you are trying to access
use an event handler (like DOM Ready):
Such:
$( function () {
$("#myLink").click(function () {
$('#newPage').transition({top: '0%' });
});
} );
use delegated events
Such:
$(document).on("click", "#myLink", function () {
$('#newPage').transition({top: '0%' });
});
Edit; sorry you already did that.
Try puttting your js file Under the js library file.

Trouble linking javascript from external file to HTML [duplicate]

I'm pretty new to JS and jQuery, and i'm trying to make a subtitles player using them. Unfortunately, i'm stuck in a very early stage.
When I'm trying to select some HTML elements through a .js file, it acts like it can't locate the element I'm asking for, and nothing happens. If I try to alert the value or the HTML of the elements, it alerts undefined.
So this is the code:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="jquery-2.1.3.min.js"></script>
<script src="script.js"></script>
<style type="text/css">
body{
margin: 0px;
padding: 0px;
}
#wrapper{
width: 150px;
text-align: center;
background: -webkit-gradient(linear, left top, right bottom, color-stop(0%,#75bdd1), color-stop(14%,#75bdd1), color-stop(100%,#2294b3));
padding: 10px 2px;
}
h3{
font-family: Arial, Helvetica, sans-serif;
}
img{
width: 50px;
margin: 0 auto;
}
input{
display: none;
}
</style>
</head>
<body>
<div id="wrapper">
<h3>Select subtitles file</h3>
<img src="browse.png" alt="browse">
</div>
<input type="file" accept=".srt" id="file">
</body>
</html>
script.js
$("div").click(function () {
console.log('loaded');
});
Thanks.
Because your script tag is above the HTML defining the elements that it acts on, it can't find them because they don't exist as of when that code runs. Here's the order in which things are happening in your page:
The html and head elements are created
The meta element is created and its content noted by the parser
The script element for jQuery is created
The parser stops and waits for the jQuery file to load
Once loaded, the jQuery file is executed
Parsing continues
The script element for your code is created
The parser stops and waits for your file to load
Once loaded, your script code is run — and doesn't find any elements, because there are no div elements yet
Parsing continues
The browser finishes parsing and building the page, which includes creating the elements you're trying to access in your script
Ways to correct it:
Move the script elements to the very end, just before the closing </body> tag, so all of the elements exist before your code runs. Barring a good reason not to do this, this is usually the best solution.
Use jQuery's ready feature.
Use the defer attribute on the script element, but beware that not all browsers support it yet.
But again, if you control where the script elements go, #1 is usually your best bet.
When you call the .click() method the dom is not fully loaded.
You have to wait till everything in DOM is loaded.So you have to change your script.js to this:
$(document).ready(function(){
$("div").click(function () {
console.log('loaded');
});
});
You should execute your script after DOM Ready event. In jquery it makes so:
$(function(){
$("div").click(function () {
console.log('loaded');
})
});
$(document).on('click', "element" , function (ev) {
console.log('loaded');
})
})

call functions onload of page in jquery

I want to make the make the slideDown function onload of my page.
When i removed the line: $("#flip").click(function() in the following code in order to make the function execute onload of page not in click, it didn't work.
How can i call a function onload of page or when some condition happen?
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown("slow");
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}
#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>
<div id="flip">Click to slide down panel</div>
<div id="panel">Hello world!</div>
</body>
</html>
Try something like this:
$(document).ready(function(){
$("#panel").slideDown("slow");
});
Simply change this
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown("slow");
});
});
to
$(document).ready(function(){
$("#panel").slideDown("slow");
});
You need to call on the document load as well.
$(document).ready(function(){
// this will run on document load
$("#panel").slideDown("slow");
// this will run every time you click on the div and you can add your custom logic to slide it up or down here
$("#flip").click(function(){
$("#panel").slideDown("slow");
});
});
Here is demon on js fiddle
The problem with your code is that you're invoking slideDown() only when someone clicks on your flip element but you wish to do it on page load, so you can use jQuery's document.ready handler itself do that
$(document).ready(function(){
$("#panel").slideDown("slow");
});
This will slideDown the panel when DOMContentLoaded event is fired which happens when all your scripts and markup are downloaded but your css and images are still downloading.
If you really want to slideDown the panel, only when the page is completely loaded i.e., markup,all scripts, images and css files are downloaded and processed, then you can listen for load event of the window like this
$(window).load(function(){
$("#panel").slideDown("slow");
});

Categories

Resources