To speed up the page loading time, I want to load the JS scripts after the page content has loaded.
I found this helpful article which explains how to do this when you have a single JS file: https://varvy.com/pagespeed/defer-loading-javascript.html
The solution goes like this:
<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "yourSingleJSFile.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
In my case, I have 4 different js files: jQuery, main.js and index.js that are starting with $(document).ready(...); and define a function initMap(), and maps.googleapis.com. Therefore I changed the code to
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js";
document.body.appendChild(element);
var element = document.createElement("script");
element.src = "/resources/js/main.js";
document.body.appendChild(element);
var element = document.createElement("script");
element.src = "/resources/js/index.js";
document.body.appendChild(element);
var element = document.createElement("script");
element.src = "https://maps.googleapis.com/maps/api/js?key=***mysecetrkey**&callback=initMap";
document.body.appendChild(element);
Each time I load the page, I find a JS error in the console. There are two errors that I spotted so far:
First
ReferenceError: $ is not defined index.js:9:5
I don't understand what is happening here. It seems like index.js was included before jquery was loaded. But how come the error is not thrown in main.js?
Second
validValueError: initMap is not a function
It seems to me that googleapis.com js is already loaded but index.js is missing (since I define function initMap() there).
How can I force the scripts to load sequently after the page content has loaded?
If the scripts have dependencies towards each other you need to make sure that the dependencies loads first. You can nest the script loading like so:
var jqueryElement = document.createElement("script");
jqueryElement.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js";
var mainElement = document.createElement("script");
mainElement.src = "/resources/js/main.js";
var indexElement = document.createElement("script");
indexElement.src = "/resources/js/index.js";
var googleApiElement = document.createElement("script");
googleApiElement.src = "https://maps.googleapis.com/maps/api/js?key=***mysecetrkey**&callback=initMap";
// add the first script element
document.body.appendChild(jqueryElement);
jqueryElementElement.onload = function () {
document.body.appendChild(googleApiElement);
}
googleApiElement.onload = function () {
document.body.appendChild(mainElement);
document.body.appendChild(indexElement)
}
I'm just guessing your dependency order.
Related
I try to add js files dynamically.
I found several guides for that and in Page inspector, they all seem like they work…
However, I cannot reference any code in the newly added files.
My three code examples that look like they work fine... but don't.
//v1
var th = document.getElementsByTagName('head')[0];
var s = document.createElement('script');
s.setAttribute('type', 'text/javascript');
s.setAttribute('src', scriptName);
th.appendChild(s);
DevExpress.localization.loadMessages(RddsDataNavigator_LanguagePack_en);
//v2
var s = document.createElement('script');
s.setAttribute('src', scriptName);
document.head.appendChild(s);
DevExpress.localization.loadMessages(RddsDataNavigator_LanguagePack_en);
//v3
let myScript = document.createElement("script");
myScript.setAttribute("src", scriptName);
document.head.appendChild(myScript);
DevExpress.localization.loadMessages(RddsDataNavigator_LanguagePack_en);
do i have to append the scripts differently or is my reference call wrong / not possible?
the Guides that exactly explain my requirement seem somehow not to work for me ?!
https://www.kirupa.com/html5/loading_script_files_dynamically.htm
Dynamically adding js to asp.net file
Thanks in advance for any help
The three methods to add a script element are essentially the same*.
As dynamically added script elements do not load the resources synchronously, you need to listen to the load event on the global object. DOMContentLoaded is another idea, but it fires too soon as it does not wait for resources to have loaded.
Here is a demo with loading jQuery asynchronously. The output shows the type of the jQuery variable, which will be "function" once that resource is loaded:
let scriptName = "https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.js";
// v3
let myScript = document.createElement("script");
myScript.setAttribute("src", scriptName);
document.head.appendChild(myScript);
console.log("Synchronous, jQuery =", typeof jQuery);
document.addEventListener("DOMContentLoaded", function () {
console.log("After DOMContentLoaded event, jQuery =", typeof jQuery);
});
window.addEventListener("load", function () {
console.log("After load event, jQuery =", typeof jQuery);
});
* The first version also defines the type attribute, but the HTML5 specification urges authors to omit the attribute rather than provide a redundant MIME type.
Consider this working example:
// dyn.js
window.zzz = 1;
<!--index.html-->
<html>
<head>
<script>
function includeJs(url)
{
if (!url) throw "Invalid argument url";
var script = document.createElement("script");
script.src = url;
document.head.appendChild(script);
}
includeJs("dyn.js");
function documentLoaded()
{
alert(window.zzz)
}
</script>
</head>
<body onload="javascript:documentLoaded()">
</body>
</html>
An obvious difference between your code and this is that the sample above loads the script during the document loading and the usage of the script code happens after the document has finished loading.
If you need to do a late-loading of a dynamic script depending on some run-time parameters, here are some options:
If you have control over the dynamically-loading script, you could add a function in your loader script and call it at the last line of the dynamically-loading script:
// dyn.js
window.zzz = 1;
if(typeof(dynamicLoadingFinished) != "undefined") dynamicLoadingFinished();
<!--index.html-->
<html>
<head>
<script>
function includeJs(url)
{
if (!url) throw "Invalid argument url";
var script = document.createElement("script");
script.src = url;
document.head.appendChild(script);
}
function documentLoaded()
{
includeJs("dyn.js");
window.dynamicLoadingFinished = function()
{
alert(window.zzz)
}
}
</script>
</head>
<body onload="javascript:documentLoaded()">
</body>
</html>
Another possible approach would be to use the good old XMLHttpRequest. It will allow you yo either force synchronous loading (which is not advisable because it will block all JavaScript and interactivity during loading, but in certain situations can be of use):
// dyn.js
window.zzz = 1;
<!--index.html-->
<html>
<head>
<script>
function includeJs(url)
{
if (!url) throw "Invalid argument url";
var request = new XMLHttpRequest();
request.open("GET", url, false);
request.send();
var script = document.createElement("script");
script.text = request.responseText;
document.head.appendChild(script);
}
function documentLoaded()
{
includeJs("dyn.js");
alert(window.zzz)
}
</script>
</head>
<body onload="javascript:documentLoaded()">
</body>
</html>
or load the script asynchronously and wait for the request to finish:
// dyn.js
window.zzz = 1;
<!--index.html-->
<html>
<head>
<script>
function includeJs(url, finished)
{
if (!url) throw "Invalid argument url";
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function ()
{
if (request.readyState == 4 || request.readyState == 0)
{
if (request.status == "200")
{
var script = document.createElement("script");
script.text = request.responseText;
document.head.appendChild(script);
return finished();
}
else throw request.responseText;
}
};
request.send();
}
function documentLoaded()
{
includeJs("dyn.js", () => alert(window.zzz));
}
</script>
</head>
<body onload="javascript:documentLoaded()">
</body>
</html>
I believe the AJAX samples could be written also with the more modern fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
I have a local JS file that needs to be called using a script object. However, I am not able to get the functions to run. Here's the code snippet.
<script type="text/javascript">
var x = document.createElement("SCRIPT");
x.type = "text/javascript";
x.src = "file:///C:/scripts/localscript.js";
//one of the functions is loadData();
loadData(); //I'm getting reference error, loadData is not defined.
</script>
Thank you,
You need to create a script element and insert it in DOM (mostly under head) to load the script. When that script is loaded by the browser, whatever you return from that script will be available.
Consider sampleScript.js with below code
(function(window){
'use strict';
window.app = {
sayHi: function() {
console.log('Hey there !');
}
};
})(this);
To load this script, I do
<script>
var node = document.createElement('script');
node.src = 'sampleScript.js';
node.addEventListener('load', onScriptLoad, false);
node.async = true;
document.head.appendChild(node);
function onScriptLoad(evt) {
console.log('Script loaded.');
console.log('app.sayHi ---> ');
app && app.sayHi();
}
</script>
Taking cues, you can fit to your need. Hope this helps.
Use the onload event:
x.onload = function() { window.loadData(); }
Situation:
jQuery is dynamically loaded together with other scripts by one file javascripts.js in the <head> section of the html file
Each html file has it's own javascript code executed on jQuery(document).ready() in the <body> section of the html file
Problem:
Error: jQuery is not defined for javascript in the <body> section
Modifying the html file is not an option (+1000 files with same problem)
Example html file:
<html>
<head>
<title>JS test</title>
<script src="javascripts.js" type="text/javascript"></script>
</head>
<body>
<input type="text" class="date">
<script>
jQuery(document).ready(function() { // Error: jQuery not defined
jQuery('.date').datepicker();
});
</script>
</body>
</html>
javascripts.js:
// Load jQuery before any other javascript file
function loadJS(src, callback) {
var s = document.createElement('script');
s.src = src;
s.async = true;
s.onreadystatechange = s.onload = function() {
var state = s.readyState;
console.log("state: "+state);
if (!callback.done && (!state || /loaded|complete/.test(state))) {
callback.done = true;
callback();
}
};
document.getElementsByTagName('head')[0].appendChild(s);
}
loadJS('javascripts/jquery-1.8.3.min.js', function() {
var files = Array(
'javascripts/functions.js',
'javascripts/settings.js'
);
if (document.getElementsByTagName && document.createElement) {
var head = document.getElementsByTagName('head')[0];
for (i = 0; i < files.length; i++) {
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', files[i]);
script.async = true;
head.appendChild(script);
}
}
});
This is happening, as many in the comments have pointed out, because you are loading jQuery asynchronously. Asynchronous means the rest of the code is executed, and so your document-ready handler (DRH) line is running before jQuery is present in the environment.
Here's a really hacky way of resolving this. It involves making a temporary substitute of jQuery whose job is just to log the DRH callbacks until jQuery has arrived. When it does, we pass them in turn to jQuery.
JS:
//temporary jQuery substitute - just log incoming DRH callbacks
function jQuery(func) {
if (func) drh_callbacks.push(func);
return {ready: function(func) { drh_callbacks.push(func); }};
};
var $ = jQuery, drh_callbacks = [];
//asynchronously load jQuery
setTimeout(function() {
var scr = document.createElement('script');
scr.src = '//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js';
document.head.appendChild(scr);
scr.onload = function() {
$.each(drh_callbacks, function(i, func) { $(func); });
};
}, 2000);
HTML:
jQuery(document).ready(function() { alert('jQuery has loaded!'); });
Fiddle: http://jsfiddle.net/y7aE3/
Note in this example drh_callbacks is global, which is obviously bad. Ideally hook it onto a namespace or something, e.g. mynamespace.drh_callbacks.
I believe this simple solution should do the trick. The changed line in the html changes the jquery onload function to a regular function. The jquery onload function will sometimes happen before the jquery is loaded and we can't have that. It's unreliable. We need that function not to execute on page load, but AFTER the jquery has loaded.
To that end, the three lines I've added in the javascript.js are inside the code that is executed immediately after jQuery has finished loading. They test to see if the pageLoaded function has been defined (so you don't have to put one on every page, only the ones that need it) and then execute it if it's there.
Now, because the change to the HTML is simple, you can just do a regex search and replace on those 1000 files to fix them. Tools like Sublime, Eclipse or TextPad are suited for that task.
Cheers!
Example html file:
<html>
<head>
<title>JS test</title>
<script src="javascripts.js" type="text/javascript"></script>
</head>
<body>
<input type="text" class="date">
<script>
function pageLoaded() { // changed
jQuery('.date').datepicker();
} // changed
</script>
</body>
</html>
javascripts.js:
// Load jQuery before any other javascript file
function loadJS(src, callback) {
var s = document.createElement('script');
s.src = src;
s.async = true;
s.onreadystatechange = s.onload = function() {
var state = s.readyState;
console.log("state: "+state);
if (!callback.done && (!state || /loaded|complete/.test(state))) {
callback.done = true;
callback();
}
};
document.getElementsByTagName('head')[0].appendChild(s);
}
loadJS('javascripts/jquery-1.8.3.min.js', function() {
var files = Array(
'javascripts/functions.js',
'javascripts/settings.js'
);
if (document.getElementsByTagName && document.createElement) {
var head = document.getElementsByTagName('head')[0];
for (i = 0; i < files.length; i++) {
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', files[i]);
script.async = true;
head.appendChild(script);
}
}
if( typeof(pageLoaded) == "function" ){ // added
pageLoaded(); // added
} // added
});
You should try following workaround to load scripts synchronously:
function loadJS(src, callback) {
document.write('<scr'+'ipt src="'+src+'"><\/scr'+'ipt>');
callback();
}
IMPORTANT to note: this function should be called always before DOM is fully rendered.
I am new to jquery. I am trying to append Jquery in an HTML page in java. To include jquery.js file I have written following code:
scriptTag += "var script = document.createElement('script');" +
"script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'; " +
"script.type = 'text/javascript'; " +
"document.getElementsByTagName('head')[0].appendChild(script);" +
and then I appended following js+jquery code with it
"var script2 = document.createElement('script'); window.onload = function() {" +
"$(document).ready(function() {" +
"$(\"#identity\").hide();});};" +
"script2.type = 'text/javascript'; " +
"document.getElementsByTagName('head')[0].appendChild(script2);";
So basically I am trying to write this :
var script = document.createElement('script');
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
var script2 = document.createElement('script');
window.onload = function() {
$(document).ready(function() {
$("#identity").hide();
});
};
script2.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script2);
What I want to do is that I want my function after window load. Somehow, writing $(document).ready(function() { alone does'nt work. I get an error that $ is not defined (looks like jquery.js is not ready yet).
To avoid this problem I have used window.onload = function() {. But now I am getting error: $(document).ready is not a function. I am really confused here on how to write this thing. Is this the correct approach? Any help/guidance is highly appreciated.
[Edit]
Please note that the following code (without jquery) works fine:
window.onload = function() {
document.getElementById('identity').style.visibility='hidden';
};
[Edit]
Actually I am making a web proxy, where I download page and serve them with custom look and field. The pages does not contain any jquery files nor can I include or write HTML. I can only add my Js dynamically using java etc.
Here is some code that shows how to load a script file dynamically and also delay calling of $(document).ready until that file is loaded:
http://jqfaq.com/how-to-load-java-script-files-dynamically/
The code you use to load jquery.min.js file is called asycnhroniously. Probably this file has not been loaded at the moment you try to execute jquery function.
Therefore you should make sure that the file is loaded using a callback function.
In the following link you can find an example on how to this:
http://blog.logiclabz.com/javascript/dynamically-loading-javascript-file-with-callback-event-handlers.aspx
Also here is a working example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>index</title>
<script type="text/javascript">
function loadScript(sScriptSrc, callbackfunction) {
//gets document head element
var oHead = document.getElementsByTagName('head')[0];
if (oHead) {
//creates a new script tag
var oScript = document.createElement('script');
//adds src and type attribute to script tag
oScript.setAttribute('src', sScriptSrc);
oScript.setAttribute('type', 'text/javascript');
//calling a function after the js is loaded (IE)
var loadFunction = function() {
if (this.readyState == 'complete' || this.readyState == 'loaded') {
callbackfunction();
}
};
oScript.onreadystatechange = loadFunction;
//calling a function after the js is loaded (Firefox)
oScript.onload = callbackfunction;
//append the script tag to document head element
oHead.appendChild(oScript);
}
}
var SuccessCallback = function() {
$("#identity").hide();
}
window.onload = function() {
loadScript('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', SuccessCallback)
};
</script>
</head>
<body>
<span id="identity"> This text will be hidden after SuccessCallback </span>
</body>
You should use this code in your scriptTag variable and then you can use eval() function to evaluate the script in this variable. Also you can load the second javascript file in the callback function using jquery's getscript function
To avoid the Google Pagespeed Messeger "Parsing Javascript later" I've copied this script.
<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "http://example.com/templates/name/javascript/jquery.js";
document.body.appendChild(element);
var element1 = document.createElement("script");
element1.src = "http://example.com/templates/name/javascript/jquery.colorbox-min.js";
document.body.appendChild(element1);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else
window.onload = downloadJSAtOnload;
</script>
How could I solve it with a loop because I need one more javascript file insert into the DOM.
Greets
Ron
You can make a function like this that takes an arbitrary number of script filenames:
function loadScriptFiles(/* pass any number of .js filenames here as arguments */) {
var element;
var head = document.getElementsByTagName("head")[0];
for (var i = 0; i < arguments.length; i++) {
element = document.createElement("script");
element.type = "text/javascript";
element.src = arguments[i];
head.appendChild(element);
}
}
function downloadJSAtOnload() {
loadScriptFiles(
"http://example.com/templates/name/javascript/jquery.js",
"http://example.com/templates/name/javascript/jquery.colorbox-min.js",
"http://example.com/templates/name/javascript/myJS.js"
);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else
window.onload = downloadJSAtOnload;
If your script files have a required load order (I presume colorbox must load after jQuery, for example), you will have to do something more sophisticated than this because this loads them all asynchronously so they have no guaranteed load order. Once you need a particular load order, it's probably best to get code that someone else has written to solve this problem like RequireJS or LABjs or Google.load().
Note: I'm also appending the script files to the <head> tag which is a bit better place to put them.
When using LABjs, you are not putting the .wait() in the right place. .wait() tells the loader to wait until all PRIOR scripts are loaded before loading the next one. I think you need it like this:
$LAB
.script("templates/name/javascript/jquery.js").wait()
.script("templates/name/javascript/jquery.colorbox-min.js");