I have this code in a script we use for initializing all of our applications, it loads the jQuery from the google CDN amongst several other things that all of our applications require. Then when we load the specific program functionality we check to make sure that jquery has loaded, in case the CDN is down. The problem I am running into is it is still loading the second one. If I add a simple alert("Test"); after the line headTag.appendChild(jqTag); it works perfectly, but if I remove the alert it uses the second one. What gives?
They are loaded like so:
<script type="text/javascript" src="i-initializer.js"></script>
<script type="text/javascript" src="i-program.js"></script>
initializer script:
if(typeof jQuery=='undefined'){
var headTag = document.getElementsByTagName("head")[0];
var jqTag = document.createElement('script');
jqTag.type = 'text/javascript';
jqTag.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js';
headTag.appendChild(jqTag);
}
Then in another script we have the following:
if(typeof jQuery=='undefined'){
var header = document.getElementsByTagName("head")[0];
var qtag = document.createElement('script');
qtag.type = 'text/javascript';
qtag.src = 'http://feedback.oursite.com/scripts/jquery-1.8.3.min.js';
qtag.onload = checkjQueryUI;
header.appendChild(qtag);
}
else
{
jQCode();
}
jQCode() {
...
}
This is the technique used by HTML5 Boilerplate. First it loads the Google CDN script, then immediately checks if the global jQuery object exists -- if it doesn't, the CDN failed and a local copy is loaded instead.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.3.min.js"><\/script>')</script>
Your fallback code loads jQuery asynchronously.
That means that the rest of your scripts run before jQuery loads.
Adding an alert() call forces the rest of your code to wait (until you click OK); by the time that happens, jQuery will have loaded.
Instead, you can emit a new <script> tag using document.write() to load it synchronously.
Alternatively, you could wrap the rest of your code in a callback and call the callback(s) after jQuery loads.
If you do it this way, you should use a script loader library, which will handle all of that for you.
Related
I have some javascript that is not required for my initial page load. I need to load it based on some condition that will be evaluated client-side.
$(document).ready(function() {
let someCondition = true; // someCondition is dynamic
if (someCondition) {
var element = document.createElement('script');
element.src = 'https://raw.githubusercontent.com/Useless-Garbage-Institute/useless-garbage/master/index.js';
element.defer = true; // does this make a difference?
element.onload = function() {
// do some library dependent stuff here
document.getElementById("loading").textContent = "Loaded";
};
document.body.appendChild(element);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="loading">Loading...</h1>
Does it make a difference (in terms of how browser will treat the script tag), if a new tag created using javascript, after document is ready, has 'defer' attribute or not? I think there is no difference, but how can I say for sure?
I believe I understand how deferred scripts behave when script tag is part of the initial html (as described here). Also, this question is not about whether element.defer=true can be used or not (subject of this question).
No that doesn't make any difference, the defer attribute is ignored in case of "non-parser-inserted" scripts:
<script defer src="data:text/javascript,console.log('inline defer')"></script>
<script>
const script = document.createElement("script");
script.src = "data:text/javascript,console.log('dynamic defer')";
script.defer = true;
document.body.append(script);
</script>
<!-- force delaying of parsing -->
<script src="https://deelay.me/5000/https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Look at your browser's console or pay attention to the logs timestamps to see that the dynamically inserted script actually did execute while we were waiting for the delayed script to be fetched.
There's a difference between adding them to the function and adding directly the CDN ( especially in your case ).
Let's look at the code execution of the above-mentioned code first,
You have added the jquery CDN first ( without defer ) so that loads first.
$(document).ready will be fired once after the complete load of jquery.
There'll be the creation and insertion of a new script tag to the dom.
Download the https://raw.githubusercontent.com/Useless-Garbage-Institute/useless-garbage/master/index.js asynchronously.
Let's look at another approach: adding CDN to the code:
Your DOM will have 2 script tags.
Both will start loading based on the type of load parallelly ( defer async etc ).
Notice you are not waiting for the dom ready event to load the second script.
I suggest adding only the main JS part in a js file and adding it to the CDN. Others can wait load with the delay.
In case you are really needed with a js src, then don't load it the first way since it waits for the complete page load.
I suggest you read and look at web-vitals and SEO for this.
and for your other question, yes you can add defer attribute with element.defer=true to the elements while creating and loading to DOM.
Hope this answer helps you!
Feel free to comment if you get any errors or doubts.
I think the JQuery Arrive lib will solve your case.
I have script (myscript.js) which create div and animate div in any HTML page. my script is using Jquery animation function
I am currently using following code (it's sample snippet)
<script src="jquery.js"><script>
<script src="myscript.js"><script>
But is this possible to use only following code which can automatically add JQuery library also?
<script src="myscript.js"><script>
Insert this on top of your myscript.js
var h=document.getElementsByTagName('head')[0];
var s=document.createElement('script');
s.type='text/javascript';
s.src='http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js';
h.appendChild(s);
but you will have to wait until script loaded using waitforload function
function w4l(){
if (typeof jQuery != "function"){
setTimeout("w4l()", 1000);
return;
}else{
//Do Jquery thing
}
}
w4l();
or just simply copy all jquery.js code file into your myscript.js, AKA merge 2 file into one
To make sure that the rest of myscript.js doesn't get executed before jQuery is loaded, use something like this:
function dostuff() {
//animate elements, etc.
}
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'jquery.js';
script.onreadystatechange = dostuff;
script.onload = dostuff;
head.appendChild(script);
Note: it's a bit unclear why you wouldn't want to explicitly add the jQuery part in your head.
Using JavaScript, is there a way to detect whether or not an external script (from a third-party vendor) has completely loaded?
The script in question is used to pull in and embed the markup for a list of jobs and, unfortunately, doesn't make use of any variables or functions. It uses document.write to output all of the content that gets embedded in my page.
Ideally, I'd like to display some kind of loading message while I'm waiting for the external script to load, and if it fails to load, display a "We're sorry, check back later..." message.
I'm using jQuery on the site, but this external script is called before I make the jQuery call.
Here's what the document.write stuff from the external script looks like:
document.write('<div class="jt_job_list">');
document.write("
<div class=\"jt_job jt_row2\">
<div class=\"jt_job_position\">
Position Title
</div>
<div class=\"jt_job_location\">City, State</div>
<div class=\"jt_job_company\">Job Company Name</div>
</div>
");
Attach an function to the load event:
<script type="text/javascript" src="whatever.js" onload ="SomeFunction()" />
As far as your loading... problem goes, try displaying a div for loading and then just display:none-ing it in your onload function. Make sure to handle cases where your script fails to load too, though.
Script tags block downloads, so as long as the content dependent on your script is below where your script it loaded, you should be fine. This is true even if the script is in-line in the body of your page.
This website has a great example of how this works.
This obviously does not work if you're loading the scripts asynchronously.
Scripts without async or defer attributes are fetched and executed immediately, before the browser continues to parse the page.
Source: MDN
You could put a script block after it on the page:
<script src="external_script.js"></script>
<script type="text/javascript">
ExternalScriptHasLoaded();
</script>
Thanks for the assistance above, especially ngmiceli for the Steve Souders link!
I decided to take what's probably a "lazy" approach, and also forego the "loading" message:
$(document).ready(function(){
if ($('.jt_job_list').length === 0){
$('#job-board').html("<p>We're sorry, but the Job Board isn't currently available. Please try again in a few minutes.</p>");
};
});
Pretty simple, but I'm looking to see if an element with the .jt_job_list class is in the dom. If it isn't, I display an error message.
This worked for me: it does however, rely on the newer querySelector interface which most modern browsers support. But if you're using really old browsers, you can use getElement... and run a for loop.
function loadJS(file, callback, error, type) {
var _file = file ;
var loaded = document.querySelector('script[src="'+file+'"]') ;
if (loaded) {
loaded.onload = callback ;
loaded.onreadystatechange = callback;
return
}
var script = document.createElement("script");
script.type = (typeof type ==="string" ? type : "application/javascript") ;
script.src = file;
script.async = false ;
script.defer = false ;
script.onload = callback ;
if (error) {
script.onerror = error ;
}
else {
script.onerror = function(e) {
console.error("Script File '" + _file + "' not found :-(");
};
}
script.onreadystatechange = callback;
document.body.appendChild(script);
}
You could give what ever your looking for an ID
and check whether not the ID has been loaded using document.getElementById("ID");
Is that what your looking for not sure I fully understand?
I am using Google Custom Search Engine with their new auto-completion feature. I want this whole javascript to be loaded AFTER the page itself is loaded. The original Google code is this:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('search', '1');
google.setOnLoadCallback(function() {
google.search.CustomSearchControl.attachAutoCompletion(
'some-long-unique-id',
document.getElementById('q'),
'cse-search-box');
});
</script>
<script type="text/javascript" src="http://www.google.com/cse/brand?form=cse-search-box&lang=cs"></script>
I have transformed this code using tutorial about JS dynamic loading to this code:
(function() {
var goog = document.createElement('script'); goog.type = 'text/javascript';
goog.src = 'http://www.google.com/jsapi';
var cse = document.createElement('script'); cse.type = 'text/javascript';
cse.src = 'http://www.google.com/cse/brand?form=cse-search-box&lang=cs';
goog.onload = function() {
google.load('search', '1');
google.setOnLoadCallback(function() {
google.search.CustomSearchControl.attachAutoCompletion(
'some-long-unique-id',
document.getElementById('q'),
'cse-search-box');
});
};
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(cse, s);
s.parentNode.insertBefore(goog, s);
})();
Well, even though I think my solution should work(the same way has Google changed their Analytics on-demand asynchronous code), it doesn't. The page loads fine and as soon as CSE loads, the page goes blank. Something clears the DOM, I suppose its some kind of "Google thing" ? Can someone bring some light on this problem and possibly a working solution ?
Thanks
OK, so by checking Google Loader Developer's Guide and by lots of trying-and-testing I've figured how to change my code so it works as I expected in my question:
(function() {
var goog = document.createElement('script'); goog.type = 'text/javascript';
goog.src = 'http://www.google.com/jsapi';
goog.onload = function() {
google.load('search', '1', {"callback": function() {}});
google.setOnLoadCallback(function() {
google.search.CustomSearchControl.attachAutoCompletion(
'some-long-unique-id',
document.getElementById('q'),
'cse-search-box');
});
};
var cse = document.createElement('script'); cse.type = 'text/javascript';
cse.src = 'http://www.google.com/cse/brand?form=cse-search-box&lang=cs';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(cse, s);
s.parentNode.insertBefore(goog, s);
})()
The main thing is this line:
google.load('search', '1', {"callback": function() {}});
If you don't specify callback (at least empty function as I do), then the whole page goes blank, when Google's CSE loads. I have no idea why, but it works fine now with this dummy callback function.
Hope it helps someone with the same problem.
I guess you can use some js loader (eg yepnope) that allows you to load js on demand and add a callback.
I don't fully-understand what you're trying to achieve. You've asked for someone to suggest how to 'correct' your code, but you haven't given any context, or what you actually want the end-result to be.
Also, the updates you've provided with the function()s you've written- it's not clear how these are being called. In the when the document readyState is complete?
Firstly, I'd suggest using jQuery to wrap up the JavaScript stuff. Yes, Google provide onload events and other helpers for their API, but jQuery will apply to any Javscript, there's no point in using two Javascript frameworks where you don't have to.
The jQuery might be like this:
<script type="text/javascript" language="javascript" src="/js/jquery/jquery-1.4.2.min.js"></script>
<script type="text/javascript" language="javascript">
// Use the jQuery document load functionality.
$(document).ready(function ()
{
// Load the Google API asynchronously. The callback 'GoogleApiLoaded' will be called when the script is fully-loaded.
$.getScript("http://www.google.com/jsapi?key=yourkey", GoogleApiLoaded);
// Load other scripts, do other init code here (non-Google-dependent).
});
function GoogleApiLoaded()
{
// Google-related init here.
// Load the custom search API.
// (Could make the callback an in-line function).
$.getScript("http://www.google.com/cse/brand?form=cse-search-box&lang=cs", CustomSearchApiLoaded);
}
function CustomSearchApiLoaded()
{
google.load('search', '1', LoadCustomSearchControl);
}
function LoadCustomSearchControl()
{
google.search.CustomSearchControl.attachAutoCompletion('some-long-unique-id', document.getElementById('q'), 'cse-search-box');
}
</script>
It might be helpful to break the code apart into different functions, in order to track-down more easily where the problem is. That you have to put in an optional callback on the 'google.load()' function is strange- it may be a bug in the Google code, there are some floating around.
I've used google.load('search', '1', LoadCustomSearchControl), rather than the google.setOnLoadCallback, because as far as I can see they should do the same thing, and using a callback on load() is neater, in my view.
I'd strongly advise you use jQuery (or any JavaScript framework), as it makes life a lot easier.
I'd be interested to see whether what I've suggested works, and if not where it goes wrong. (Make sure to add-in your own JSAPI key).
Is it possible to load certain scripts like
<script type="text/javascript" src="somescript.js"></script>
when the rest of the page has loaded?
Imagine I have a few larger script files like this that are not needed when the page is loaded. E.g. I'm using the Google Maps API that is only used when a button is clicked (so not on page load).
Is it possible to load the rest of the page first, before processing all those script tags in my head?
In JQuery you could do this on document ready
$.getScript("somescript.js", function(){
alert("Script loaded and executed.");
});
simply you can add into that script file defer parameter
<script src="pathToJs" defer></script>
you can check this question as well
It is possible. I was doing a similar thing in an AJAX intensive site, but I was loading the Google Charts API. Here is the code I used to load the Google Charts API when a button was clicked on the page.
function loadGoogleChartsAPI() {
var script = document.createElement("script");
// This script has a callback function that will run when the script has
// finished loading.
script.src = "http://www.google.com/jsapi?callback=loadGraphs";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
}
function loadGraphs() {
// Add callback function here.
}
This uses a callback function that will run when the script has loaded.
No one mentioned these?
$(window).load(function(){
// do something
});
or
$(window).bind("load", function() {
// do something
});
$(document).ready(function() {
var ss = document.createElement("script");
ss.src = "somescript.js";
ss.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(ss);
});
Please see my code. The onload event will occur when the script has finished loading. Or the onerror event will occur.
function loadJavaScript() {
var script = document.createElement("script");
script.src = "javaScript.js";
script.type = "text/javascript";
script.onload = function () {
console.log('script was loaded successfully');
}
script.onerror = function (e) {
console.error('script.onerror');
}
document.getElementsByTagName("head")[0].appendChild(script);
}
Thanks to answer.
Also see my code of the load of the script.
use the getScript method of jquery! or try simply to put this script on the end of the page?
Yes, this is possible by dynamically injecting the JavaScript files from code. There are lots of libraries which you can use:RequireJS, HeadJS etc. Recently I found this document which compares lots of JavaScript loader libraries.
To just allow the page to show before your script is loaded, use the async attribute:
<script src="//url/to/script.js" async></script>
To hide the loading spinner in the browser, append the script tag after the page finished loading:
<script>
document.addEventListener('DOMContentLoaded', function() {
var script = document.createElement('script');
script.src = '//url/to/script.js';
document.getElementsByTagName('body')[0].appendChild(script);
});
</script>
Yep, that's completely possible. Add an onLoad="foo();" event to your <body> tag and have it invoke your scripts. You'll need to wrap your external JS in a function and do something like:
//EXTERNAL JS (jsstuff.js)
function Mojo() {
document.getElementById('snacks').style.visibility = "visible";
alert("we are victorious!");
}
//YOUR HTML
<html>
<head>
<script type='text/javascript'></script>
</head>
<body onLoad='Mojo();'>
<div id='snacks'>
<img src='bigdarnimage.png'>
</div>
</body>
</html>