Load an external javascript file before another? - javascript

I have two external javascript files within my html page.
I need to make sure that the first file, script1.js, is run before my second script, script2.js.
I have them within the body of my html page; how can I ensure that script2 is not used until the functions in script1 are run?
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<!-- Script 1 -->
<script src="js/script1.js"></script>
<!-- Script 2 -->
<script src="js/script2.js"></script>
</body>
</html>

The browser will execute the scripts in the order it finds them. If you call an external script, it will block the page until the script has been loaded and executed.
So if your code is :
<body>
<!-- Script 1 -->
<script src="js/script1.js"></script>
<!-- Script 2 -->
<script src="js/script2.js"></script>
</body>
Script 1 will be run before Script 2.

<script> tag manage it for you... but read on...
JavaScript is synchronous, that means things it will executed line by line by default...
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<!-- Script 1 -->
<script src="js/script1.js"></script> <!-- first gets executed and get finished -->
<!-- Script 2 -->
<script src="js/script2.js"></script> <!-- then second gets executed and get finished -->
</body>
</html>
But at the same JavaScript could be asynchronous too...
So there is an attribute for <script> tag which make the loading asynchronous... async attribute on script tag...
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<!-- Script 1 -->
<script src="js/script1.js" async></script> <!-- load asynchronously -->
<!-- Script 2 -->
<script src="js/script2.js" async></script> <!-- load asynchronously -->
</body>
</html>
Definition and Usage The async attribute is a boolean attribute.
When present, it specifies that the script will be executed
asynchronously as soon as it is available.
Note: The async attribute is only for external scripts (and should only be used if the src attribute is present).
Note: There are several ways an external script can be executed:
If async is present: The script is executed asynchronously with the
rest of the page (the script will be executed while the page continues
the parsing) If async is not present and defer is present: The script
is executed when the page has finished parsing If neither async or
defer is present: The script is fetched and executed immediately,
before the browser continues parsing the page

You can't check if it was running. You could only watch the loading with jQuery and append the second script whenever it's finisished.
HTML:
<script id="first" src="js/script1.js"></script>
JS:
$("#first").on("load", function() {
$("head").append('<script src="js/script2.js"></script>');
});

Te ensure you load all your scripts in the proper way, you have to use some dependency handling library, like RequireJS, that allow you to execute the code just when your declared dependencies are loaded properly.
If you prefer, you could do it by yourself using something like jQuery.getScript, or do it in all javascript take that as an example.

I understand that you're using javascript, but if you have jQuery, you can use (2) document.ready functions like so, and load those script files. Each document.ready will queue (using deferred) for each one.
$(function() { // same as document.ready
$.getScript('script1.js');
});
$(function() {
$.getScript('script2.js');
});
Taken from:
Multiple $(document).ready functions
How to load a script on $(document).ready()/onDeviceReady() of jquery-mobile/phonegap

function loadJS(file) {
// DOM: Create the script element
var jsElm = document.createElement("script");
// set the type attribute
jsElm.type = "application/javascript";
// make the script element load file
jsElm.src = file;
// finally insert the element to the body element in order to load the script
document.body.appendChild(jsElm);
}
myScript.src = 'http://code.jquery.com/jquery-2.1.4.min.js';
myScript.onload = function() {
loadJS("js/script2.js")
};

Your first script add new function .
function firstScriptFunction(){
//i have done nothing here
}
Your Html page
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<!-- Script 1 -->
<script src="js/script1.js"></script>
<!-- Script to load script 2 -- >
<script type="text/javascript">
function loadSecondScript() {
if (!(typeof firstScriptFunction == 'function')) {
window.setTimeout(loadSecondScript, 3000);
}
else {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'js/script2.js';
document.getElementsByTagName('body')[0].appendChild(script);
}
}
$(document).ready(function(){
loadSecondScript();
});
</script>
</body>
</html>

Related

Inclusion of external js file and calling a function inside the external js file does not work with same script tag

Why it is necessary to first include an external js file and call any functiont later on with new script tags ?
I am testing with the code:
test.html
<html>
<head>
</head>
<body>
<script src=test.js>test();</script>
</body>
</html>
test.js
function test(){
alert(1);
}
It does not show an alert popup.
But when I include test.js separately either in body or head with the code:
test.html
<html>
<head>
</head>
<body>
<script src=test.js></script>
<script>test();</script>
</body>
</html>
It does show a pop-up indeed. Does it have anything to do with the HTML parser? I am not even getting a ReferenceError displayed in the browser console so test has a reference but it is not executing.
Code in the global namespace must be loaded in the order such that executed code must first be defined.
For example, if a.js had...
var a = function() {
alert('a');
}
...and b.js had...
a()
...then you wouldn't want to include b.js before a.js, or a() won't be available.
For above,
<script src=test.js></script>
<script>test();</script>
again it is the same way: First include file, then run its contents.
this happens because when you specify a src attribute you told the browser not to look for javascript inside this tag but instead from an external one

jQuery doesn't work in an external js file

I'm a beginner of jQuery. I wanne write my jQuery in an external js file instead of in the head of html file, but it failed.
index.html:
<!DOCTYPE html>
<head>
<script src="js/func.js"></script>
</head>
<body>
<p id="response">response is shown here</p>
<button id="bt_testJQ">jq test</button>
</body>
</html>
func.js
document.write("<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>")`
`$(document).ready(function () {
$("#bt_testJQ").click(function () {
$("#response").toggle();
})
})
`
This has nothing to do with putting the code in an external file, you'd have the same problem if it was inline.
document.write's output is placed after the <script></script> element and parsed by the HTML parser when the script has finished running. Effectively, you are:
setting up jQuery to load
Trying to use jQuery
actually loading jQuery
You can't use jQuery before you load it.
The simple solution to this is to use two script elements in the HTML and load jQuery first.
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>
<script src="js/func.js"></script><!-- with the document.write line removed -->
just wanna to avoid importing the jquery in every html file.
This is best handled by either:
Using a template system.
Using a build system that combines the contents of all your scripts, including third party libraries, into a single file.
A better way of doing this is have the jquery library called at the head and have your external js script at the last part of the body of your html
html code
<!DOCTYPE html>
<head>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>
</head>
<body>
<p id="response">response is shown here</p>
<button id="bt_testJQ">jq test</button>
<script src="js/func.js"></script>
</body>
</html>

HTML Page Loading

I need the following:
I have an html page, which has declared several javascripts inside the body tag. However, I must make an asynchronous process prior to loading all of these components and render the page, and then continue the process. Any tips on how to solve this?
Thank you.
My code structure:
<html>
<script>
function loadFromServer() {
//this operation is async, and I need to`enter code here` process this before load
//the scripts declareds in body.
}
</script>
<body>
//content
//js loads
</body>
</html>
Have you tried putting the scripts declaration after the body tag?
<body>
...
</body>
<!-- script declarations here -->
<script src=""></script>
<script src=""></script>
<script src=""></script>

When does the external script imported by the loadasync function get executed?

// Asynchronously load and execute a script from a specified URL
function loadasync(url) {
var head = document.getElementsByTagName("head")[0]; // Find document <head>
var s = document.createElement("script"); // Create a <script> element
s.src = url; // Set its src attribute
head.appendChild(s); // Insert the <script> into head
}
JavaScript:The Definite Guide introduces such a function that loads external scripts asynchronously. But I have no idea when the imported script executes.As soon as the script that loads it finishes running? Or, after the load event on window happens?
Considering the purpose of the function or the reason why it is introduced, the answer is not likely the first case, and the following test case demonstrates:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<script type="text/javascript">
(function loadasync(url) {
var head = document.getElementsByTagName("head")[0];
var s = document.createElement("script");
s.src = url;
head.appendChild(s);
}("external.js"));
</script>
</head>
<body>
<h1>This is a test page.</h1>
</body>
</html>
The content in external.js:
alert("external script executed, dead loop");
while(true);
The "h1" element renders normally without being blocked by the dead loop caused by the external script. It means that the imported external script executes at a later time, instead of as soon as the script that loads it finishes running. But when exactly?
I believe it's still executes right after it loads, the h1 is render is because the js file still takes time to load, while others can finish their rendering, I change your codes to make some test:
html part:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<script type="text/javascript">
(function loadasync(url) {
var head = document.getElementsByTagName("head")[0];
var s = document.createElement("script");
s.src = url;
head.appendChild(s);
}("./js/external.js"));
window.onload = function() {
alert("window loaded");
};
</script>
</head>
<body>
<h1>This is a test page.</h1>
<div id="test">See the page</div>
</body>
</html>
external.js part:
alert("external script executed, dead loop");
var ele = document.getElementById("test");
alert(ele.innerText);
In my broswer, the alert's sequence is external script executed, dead loop => See the page => window loaded.
So, when you executes the script, it add script tag to head and start to load it, while other parts of page keep rendering.
However, as you add something that needs to load, window.onload will wait until that script is loaded.
And we can observe from the alert sequence that the scripts execute itself right after its loaded.

how must my javascript look like to run at the end of my ASP.NET page

this code is put at the top of my asp.net page:
function Test(HtmlDocument)
{
}
How can I execute this javascript function at the end of my page?
Just invoke the function in <script> tags immediately before the </body> tag.
<html>
<head>
<!-- snip -->
</head>
<body>
<!-- snip -->
<script>
Test(document);
</script>
</body>
</html>
Simply put
<script>Test(document);</script>
In the end of your html
The best way to achieve this is using windows.onload. The event can be used to perform some task as soon as the page finishes loading. Here is an example:
<script type="text/javascript">
function my_code(){
alert(" Alert inside my_code function");
}
window.onload=my_code();
</script>
Or you can put the function at the bottom of the code without the function declaration
<script>
Your javascript code here
</script>
The easy way is to drop a script manager on the page (anywhere within the body of the page) then put something like this on the page ...
<script type="text/javascript">
Sys.Application.add_load(function () {
// do your thing
});
</script>
That executes client side when the document has finished loading.

Categories