Can stripe.js be deferred and used with some ready - callback that i can't find in the docs?
This is what i wanna do:
<script src="https://js.stripe.com/v2/" async></script>
And then in my app:
function stripeReadyHandler () {
//do stuff
}
Turns out, there's a standards compliant way to do this:
<script src="https://js.stripe.com/v2/" async onload="stripeReadyHandler()"></script>
and then:
function stripeReadyHandler () {
//this will definitely do stuff ( if you're above IE9 of course
}
Or, with JavaScript:
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://js.stripe.com/v2/';
document.body.appendChild(script);
script.onload = function() {
Stripe.setPublishableKey(publishableKey);
// do stuff
};
Related
I have the following code in a script.js file that I call in my html file:
function loadScript(url)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.async = false;
head.appendChild(script);
}
loadScript('https://polyfill.io/v3/polyfill.min.js?features=es6')
loadScript('https://cdn.jsdelivr.net/npm/mathjax#3/es5/tex-mml-chtml.js')
loadScript('https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/highlight.min.js')
hljs.initHighlightingOnLoad();
I use this code because I want to call only one .js file in my html instead of multiple .js files.
The first two scripts that I load to call MathJax work fine. The third script to call highlight.js however does not run.
When I paste all the code from the file 'highlight.min.js' into the my script.js file, the javascript does run normally when I open the html.
I don't understand why loading the 'highlight.min.js' file with the loadScript() does not work, or what I can do to get it to work. Any help is appreciated.
The script loading is asyncronous, so when hljs.initHighlightingOnLoad() is called the scripts are not loaded yet.
Alternative 1
You can modify your loadScript() function to make it work with promises, which resolve when the script is loaded (taken from here):
function loadScript(url) {
return new Promise(function(resolve, reject) {
var script = document.createElement("script");
script.onload = resolve;
script.onerror = reject;
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
});
}
Now you can call your code and be sure that all libraries are loaded before calling hljs.initHighlightingOnLoad():
(async function init() {
await loadScript('https://polyfill.io/v3/polyfill.min.js?features=es6');
await loadScript('https://cdn.jsdelivr.net/npm/mathjax#3/es5/tex-mml-chtml.js')
await loadScript('https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/highlight.min.js')
hljs.initHighlightingOnLoad();
})()
Alternative 2
You can modify your loadScript() function to make it load the scripts using defer and add an optional onload handler that you can use to call hljs.initHighlightingOnLoad():
function loadScript(url, onload)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.async = false;
script.onload = onload;
head.appendChild(script);
}
loadScript('https://polyfill.io/v3/polyfill.min.js?features=es6')
loadScript('https://cdn.jsdelivr.net/npm/mathjax#3/es5/tex-mml-chtml.js')
loadScript('https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/highlight.min.js', () => {hljs.initHighlightingOnLoad()})
Wheres your onload handler?
script.onload = function(){};
Lets not worry about errors for now...
https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement
If the libs require each other then you need to defer because the child may be smaller than the parent.
I have a js file that in which i want to include jquery. in order to include the jquery script i am using this clode:
var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
this works, I can see that incuded the script correctly. My inspector shows that it loaded the script but jquery wont work.
any ideas?
You need to make sure the script you are dynamically loading is actually loaded before attempting to use it.
To do so, use script.onload to fire a callback once the load is completed.
var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head') [0].appendChild(script);
script.onload = function () {
/* jquery dependent code here */
console.log($);
};
MDN has an example that's more adaptable to a callback you specify -
// from https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement#Dynamically_importing_scripts
function loadError (oError) {
throw new URIError("The script " + oError.target.src + " is not accessible.");
}
function importScript (sSrc, fOnload) {
var oScript = document.createElement("script");
oScript.type = "text\/javascript";
oScript.onerror = loadError;
if (fOnload) { oScript.onload = fOnload; }
document.currentScript.parentNode.insertBefore(oScript, document.currentScript);
oScript.src = sSrc;
}
Your jQuery code is not working may be caused by jQuery is not loaded yet while browser executing your jQuery code. Use function below to dynamically load jQuery with callback. Put your jQuery code inside a callback function.
function loadScript(url, callback) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url;
if (typeof(callback) === 'function') {
s.onload = s.onreadystatechange = function(event) {
event = event || window.event;
if (event.type === "load" || (/loaded|complete/.test(s.readyState))) {
s.onload = s.onreadystatechange = null;
callback();
}
};
}
document.body.appendChild(s);
}
/* Load up jQuery */
loadScript('https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', function() {
// Put your jQuery code here.
});
You need to include jQuery inside the HTML code. jQuery won't work for you because your script is loaded before jQuery is loaded.
I am trying to include jquery dynamically and i have used the following code-
index.php
<!doctype html>
<html>
<head>
<script type="text/javascript" src="includejquery.js"></script>
</head>
<body>
<div id="testing"></div>
<script type="text/javascript">
$(document).ready(function(){
$('#testing').html('<p>This is a paragraph!</p>');
});
</script>
</body>
</html>
includejquery.js
if(!window.jQuery)
{
var script = document.createElement('script');
script.type = "text/javascript";
script.async = true;
script.src = "http://code.jquery.com/jquery-2.1.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
jQuery.noConflict();
}
But jquery functionality is not working it is not printing the paragraph tag :-( Please help me out. Thanks in advance
That's not working because your $(document).ready(... line runs before jQuery loads, and so it fails because either $ is undefined (throwing a ReferenceError) or it refers to something other than jQuery. Also, you're calling jQuery.noConflict() before jQuery is loaded, and if that call did work, it would mean that $ no longer referred to jQuery at all, so $(document).ready(... still wouldn't work.
In any modern browser, you can use the load event on the script element you're adding, which tells you that the script has been loaded. Probably best to pass a callback into a call you make to includejquery.js, like this:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="includejquery.js"></script>
</head>
<body>
<div id="testing"></div>
<script type="text/javascript">
includejQuery(function($){
$('#testing').html('<p>This is a paragraph!</p>');
});
</script>
</body>
</html>
includejquery.js:
function includejQuery(callback) {
if(window.jQuery)
{
// jQuery is already loaded, set up an asynchronous call
// to the callback if any
if (callback)
{
setTimeout(function() {
callback(jQuery);
}, 0);
}
}
else
{
// jQuery not loaded, load it and when it loads call
// noConflict and the callback (if any).
var script = document.createElement('script');
script.onload = function() {
jQuery.noConflict();
if (callback) {
callback(jQuery);
}
};
script.src = "http://code.jquery.com/jquery-2.1.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
}
}
Changes there:
In includejquery.js, just define a function and wait to be called.
Have that function accept a callback.
Have it wait for the script to load.
When the script is loaded, call jQuery.noConflict and then, if there's a callback, call it and pass in the jQuery function.
In the HTML, I'm calling the function, and receiving the argument it passes me as $, so within that function only, $ === jQuery even though outside it, it doesn't (because of noConflict).
What's wrong with the implementation from the HTML5-Boilerplate?
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery_2.1.1.min.js"><\/script>')</script>
Alternative solution
(function () {
initScript().then(function (v) {
console.info(v);
var script = document.getElementById("__jquery");
script.onload = function () {
$(document).ready(function () {
// Main logic goes here.
$("body").css("background-color","gray");
});
};
});
function initScript() {
promise = new Promise(function(resolve,reject) {
try {
if(typeof jQuery == 'undefined') {
console.warn("jQuery doesn't exists");
var jQuery_script = document.createElement("script");
jQuery_script.src = "https://code.jquery.com/jquery-2.2.4.min.js";
jQuery_script.type = 'text/javascript';
jQuery_script.id = "__jquery";
document.head.appendChild(jQuery_script);
resolve("jQuery added succesfully.");
}
resolve("jQuery exists.")
} catch (ex) {
reject("Something went wrong on initScript() : ", ex);
}
});
return promise;
}
})();
I used promise because if there is no jQuery in the page we need to wait to load it first.
.ready will not fire since your script loads async.
This should the first thing to run on the page and block all other scripts in order to load the dependencies on time.
Appending to body:
function loadScript() {
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://www.mydomain/myscript.js';
script.async = true;
document.body.appendChild(script);
}
Appending to head:
function loadScript() {
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://www.mydomain/myscript.js';
script.async = true;
head.appendChild(script);
}
Usually when you include some scripts, browser will load them synchronously, step by step.
But if you set
script.async = true;
script will load asynchronously and other scripts will not waiting for them. To fix this problem you can remove this option.
There is an onload event on the script. Use that.
<!doctype html>
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "http://code.jquery.com/jquery-2.1.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
script.onload = function() {
$('#testing').html('<p>This is a paragraph!</p>');
};
};
</script>
</head>
<body>
<div id="testing"></div>
</body>
</html>
Check your browsers js console. You will probably see something like $ is undefined and not a function. It is because you are running the code in
You can try to wrap the jquery code you want to run in the readyStateChange event of the script tag. Or you can use require.js.
There is a working demo http://jsbin.com/lepapu/2/edit (Click "Run with JS")
<script>
if(!window.jQuery)
{document.write('<script src=http://code.jquery.com/jquery-2.1.1.min.js><\/script>')}
</script>
<script>
$(document).ready(function(){
$('body').html('<p>This is a paragraph!</p>');
});
</script>
The order of scripts matters.
I have a JavaScript file, which also uses jQuery in it too. To load it, I wrote this code:
function include(filename)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
head.appendChild(script)
}
include('http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js');
alert("1");
$(document).read(function(){});
alert("2");
This fires alert("1"), but the second alert doesn't work. When I inspect elements, I see an error which says that $ in not defined.
How should I solve this problem?
You need to execute any jQuery specific code only once the script is loaded which obviously might happen at a much later point in time after appending it to the head section:
function include(filename, onload) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
script.onload = script.onreadystatechange = function() {
if (script.readyState) {
if (script.readyState === 'complete' || script.readyState === 'loaded') {
script.onreadystatechange = null;
onload();
}
}
else {
onload();
}
};
head.appendChild(script);
}
include('http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js', function() {
$(document).ready(function() {
alert('the DOM is ready');
});
});
And here's a live demo.
You may also take a look at script loaders such as yepnope or RequireJS which make this task easier.
The problem here is probably that, even though you include the script, it doesn't mean it is loaded when you try to do $(document).ready(function(){});. You could look into Google Loader to prevent this problem http://code.google.com/intl/fr-FR/apis/loader/
I have a initializor.js that contains the following:
if(typeof jQuery=='undefined')
{
var headTag = document.getElementsByTagName("head")[0];
var jqTag = document.createElement('script');
jqTag.type = 'text/javascript';
jqTag.src = 'jquery.js';
headTag.appendChild(jqTag);
}
I am then including that file somewhere on another page. The code checks if jQuery is loaded, and if it isn't, adds it to the Head tag.
However, jQuery is not initializing, because in my main document, I have a few events declared just to test this. I also tried writing some jQuery code below the check, and Firebug said:
"jQuery is undefined".
Is there a way to do this? Firebug shows the jquery inclusion tag within the head tag!
Also, can I dynamically add code into the $(document).ready() event? Or wouldn't it be necessary just to add some Click events to a few elements?
jQuery is not available immediately as you are loading it asynchronously (by appending it to the <head>). You would have to add an onload listener to the script (jqTag) to detect when it loads and then run your code.
e.g.
function myJQueryCode() {
//Do stuff with jQuery
}
if(typeof jQuery=='undefined') {
var headTag = document.getElementsByTagName("head")[0];
var jqTag = document.createElement('script');
jqTag.type = 'text/javascript';
jqTag.src = 'jquery.js';
jqTag.onload = myJQueryCode;
headTag.appendChild(jqTag);
} else {
myJQueryCode();
}
To include jQuery you should use this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="jquery.js">\x3C/script>')</script>
it uses the Google CDN but provides a fallback an has a protocol relative URL.
Note: Be sure to change the version number to the latest version
if window.jQuery is defined, it will not continue to read the line since it is an or that already contains a true value, if not it wil (document.)write the value
see: theHTML5Boilerplate
also: you forgot the quotes, if jQuery is not defined:
typeof window.jQuery === "undefined" //true
typeof window.jQuery == undefined //false ,this is wrong
you could also:
window.jQuery === undefined //true
If you're in an async function, you could use await like this:
if(!window.jQuery){
let script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
await script.onload
}
/* Your jQuery code here */
If you're not, you can use (async function(){/*all the code*/})() to wrap and run all the code inside one
.
Alternatively, refactoring Adam Heath's answer (this is more readable IMO). Bottom line, you need to run the jQuery code AFTER jQuery finished loading.
jQueryCode = function(){
// your jQuery code
}
if(window.jQuery) jQueryCode();
else{
var script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
script.onload = jQueryCode;
}
Or you could also wrap it in a function to change the order of the code
function runWithJQuery(jQueryCode){
if(window.jQuery) jQueryCode();
else{
var script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
script.onload = jQueryCode;
}
}
runWithJQuery(function jQueryCode(){
// your jQuery code
})
The YepNope loader can be used to conditionally load scripts, has quite a nice, easy to read syntax, they have an example of just this on their website.
You can get it from their website.
Example taken from their website:
yepnope([{
load: 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js',
complete: function () {
if (!window.jQuery) {
yepnope('local/jquery.min.js');
}
}
}
This site code is solved my problem.
function loadjQuery(url, success){
var script = document.createElement('script');
script.src = url;
var head = document.getElementsByTagName('head')[0],
done = false;
head.appendChild(script);
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
done = true;
success();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
}
if (typeof jQuery == 'undefined'){
loadjQuery('http://code.jquery.com/jquery-1.10.2.min.js', function() {
// Write your jQuery Code
});
} else {
// jQuery was already loaded
// Write your jQuery Code
}
http://99webtools.com/blog/load-jquery-if-not-already-loaded/
This is old post but I create one workable solution tested on various places.
Here is the code.
<script type="text/javascript">
(function(url, position, callback){
// default values
url = url || 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
position = position || 0;
// Check is jQuery exists
if (!window.jQuery) {
// Initialize <head>
var head = document.getElementsByTagName('head')[0];
// Create <script> element
var script = document.createElement("script");
// Append URL
script.src = url;
// Append type
script.type = 'text/javascript';
// Append script to <head>
head.appendChild(script);
// Move script on proper position
head.insertBefore(script,head.childNodes[position]);
script.onload = function(){
if(typeof callback == 'function') {
callback(jQuery);
}
};
} else {
if(typeof callback == 'function') {
callback(jQuery);
}
}
}('https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js', 5, function($){
console.log($);
}));
</script>
Explanation you can find HERE.