This question already has answers here:
Best practice for using window.onload
(7 answers)
Closed 7 years ago.
I haven't been working with javascript before, so I am still learning the basics.
I have included two javascript files in my main file called index.html. The reason for this is to let users select which javascript file to show (diagram 1 or diagram 2) by clicking on the navigation tool bar. The problem is that both of these javascript files have a equal method called window.onload, so they replace each other. How can I prevent these two javasript files to replace each other?
First javascript file:
window.onload = function {// Preview diagram 1}
Second javascript file:
window.onload = function {// Preview diagram 2}
Here is a snip of what I have in my index.html
<script type="text/javascript" src="js/diagram1.js"></script>
<script type="text/javascript" src="js/diagram2.js"></script>
In your both diagram1.js & diagram2.js files, use:
$(window).on("load", function() {
// your init code
});
to do stuff on window load instead of registering function to window.onload.
Related
This question already has answers here:
Why doesn't document.addEventListener('load', function) work in a greasemonkey script?
(6 answers)
Why "load event not working on addEventListener()"?
(3 answers)
Closed 1 year ago.
i am trying to execute the document.addEventListener() but it is not working why ?
<html>
<head>
<title>javascript</title>
<link rel="stylesheet" href="C:\Users\SUDARSHAN\Desktop\html_UI\eventstyle.css">
</head>
<body>
<p id="p1">Welcome</p>
</body>
<script>
function f1() {
document.getElementById("p1").style.fontSize="50px";
}
document.addEventListener("load",f1);
console.log("hello");
</script>
</html>
You must append a load listener to window instead of document.
window.addEventListener("load",f1);
That being said, you cannot have a script element as a child of the html element, it must be in the head or body (which are the only allowed children of html). Always make sure your HTML is valid at all times; invalid HTML puts you in unspecified territory and tends to make things unpredictable (even if things seem to work).
Flaws in above code.
Always make sure the html tag documented correctly. For ref https://www.w3schools.com/tags/tag_doctype.asp
load event depends on window. In above code, you added the listener for document.
You can try following:
document.addEventListener('DOMContentLoaded', f1);
There are two events which are related to loading and unloading of the Document
DOMContentLoaded
readystatechange
Refer this page for windows events
https://developer.mozilla.org/en-US/docs/Web/API/Document#load_unload_events
This question already has answers here:
How Do I Add jQuery To Head With JavaScript?
(3 answers)
Closed 4 years ago.
I have a simple script that I placed inside it's own file (my_file.js). This script depends on jQuery. Obviously users can access its functionality via the script tags inside the head tags:
<head>
<script src='http://code.jquery.com/jquery-3.3.1.min.js'></script>
<script src='my_file.js'></script>
</head>
This works perfectly, since the JS is loaded sequentially. But I would like users to not have to add jQuery explicitly at the top. Is there a way my_file.js can itself load jQuery prior to its own JS, such that users only add the one file:
<head>
<script src='my_file.js'></script>
</head>
I know modules and bundlers take care of this issue, but I'm interested to see if there is an approach that allows one file to bring in its dependency, and wait until it's loaded before running the rest of the script.
Is there something like dynamic imports, such that:
import('http://code.jquery.com/jquery-3.3.1.min.js').then(module => {
// load my scripts here
});
Or AJAX in vanilla JS:
var xhr = new XMLHttpRequest()
xhr.open('GET', 'http://code.jquery.com/jquery-3.3.1.min.js')
xhr.onload = function() {
if (xhr.status === 200) {
// load my scripts here
}
else {
console.log('Request failed. Returned status of ' + xhr.status)
}
}
Everything I try runs my_file.js before jQuery. How can I make sure jQuery is loaded first, without having to place it in the tags?
Open jquery.min.js on your browser. Select all code and then copy it. Then paste it to the beginning of my_file.js.
The code should like:
/*! jQuery v3.3.1 | (c) JS Foundation and other contributors | jquery.org/license */
!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){"use st.....
// Your code here...
This question already has answers here:
Official way to ask jQuery wait for all images to load before executing something
(11 answers)
Closed 6 years ago.
I have a simply script. For example:
var rowCount = $('tr').length;
document.write(rowCount);
I want to load this after entire webpage has loaded. How can I do?
Use following script:
<script type="text/javascript">
$(document).ready(function () {
var rowCount = $('tr').length;
document.write(rowCount);
});
</script>
This question already has answers here:
eval() doesn't execute external (src=...) scripts
(2 answers)
Closed 6 years ago.
I'm using eval() to execute all <script> tags after total rewrite of a div.
$("#content").find("script").each(function(){
eval($(this).text());
});
It works well for inline-scripts, but has no effect on scripts like:
<script src="/path/to/externalScript.js"></script>
How come? Can I "force" the browser to load and execute also the external scripts?
Besides the very real issues with using eval, you are trying to eval the .text inside those script tags, which is essentially nothing.
When a <script> tag loads, it links in the external file as a resource to your page and executes the script. It does not render anything directly to the dom.
Thus you $(this).text() will return ''.
If you want to reload the external scripts, you will either need to force a page refresh, or potentially change the way you are pulling in those scripts: ex. jQuery.getScript alternative in native JavaScript
$("body").css("background", "silver");
$("button").click(function () {
$("script[src^='data:']").each(function () {
var script = document.createElement('script');
script.src = this.src;
document.body.appendChild(script);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="data:text/javascript,document.body.style.background='red'"></script>
<button>Go</button>
I have a site and I want it to randomly load a different HTML5 Javascript animation each time the page is loaded, JavaScript is by far one of the weakest of my skills and I appreciate any help in advance and if this happens to be duplicate (I've tried searching) then please vote for the question to be closed.
Basically the method I have used is a dirty one and most likely the reason its not working, basically I tried randommath and had no luck and put this down to my JS skills being extremely weak, the alternative method which looked easier doesn't work either and this is basically inserting a HTML on page load, so for example a.html and b.html which both contain different scripts.
This is what my code looks like:
HTML
<html>
<head>
<script src="js/insert.js"></script><!-- This inserts the Random Page -->
</head>
<body onload="loadExternalHTMLPage()">
<div id="injectjs"> </div>
<canvas="id"> </canvas>
<script src="js/animation-lib-pageA.js"></script><!--Library for pageA -->
<script src="js/animation-lib-pageB.js"></script><!--Library for pageB -->
</body>
</html>
Inject.js
function loadExternalHTMLPage() {
var xmlhttp;
var pagesToDisplay = ['a.html', 'b.html'];
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("jsinsert").innerHTML = xmlhttp.responseText;
}
}
var randomnumber = Math.floor(Math.random() * pagesToDisplay.length);
xmlhttp.open("GET", pagesToDisplay[randomnumber], true);
xmlhttp.send();
}
Most JS Guru's should be able to see that I'm randomly inserting a.html and b.html on page load, now this works but the problem is the scripts contained within a.html and b.html are not executing. (using firebug I can clearly see that the scripts are being inserted as intended).
so for example a and b looks like:
a.html
<script> window.onload = function () { }</script>
b.html
<script> window.onload = function () { } </script>
Basically the code within A and B are valid and work fine within this insert and I've filled the above examples as just a placeholder. A and B both contain JavaScript that executes animation contained within the canvas but it doesn't work at present and I suspect its something to do with the fact I'm loading the scripts after the page has been loaded. Thanks in advance.
You can randomly load the html for A or B and then run its animation.
This example uses jQuery which makes the task of loading remote html easier. Here is a link to the jquery .load function which replaces an existing elements html with the downloaded html: http://api.jquery.com/load/ If you want pure javascript, you can use that [messier!] alternative, but the logic remains the same.
These are the steps:
Be sure the web page has loaded,
Randomly pick A or B to load/execute,
Replace the html in #injectjs with htmlForA or htmlForB,
Wait until the html has been fully replaced,
Run the appropriate animationA or animationB.
Here is starter code. (Be sure you include the jQuery library)
<script>
window.onload(){
// randomly load html+animation A or B
if(Math.random()<.50){
$('#injectjs').load(
'yourSite.com/HtmlForA.html', // first load the html for A
function(){ animationA(); } // then run animationA
);
}else{
$('#injectjs').load(
'yourSite.com/HtmlForB.html', // first load the html for B
function(){ animationB(); } // then run animationB
);
}
}
</script>
You can always use eval() to execute the content you downloaded ... :) (not recommended).
Or you can modify the html page on server to include the random script you want before serving the page to the user (you don't state platform) since it's anyways changed at page load.