JS script sometimes not loading on Rails 5 - javascript

I want to be sure that my scripts are being loaded before I call a function.
This code is written inline on the page, it is not being loaded by application.js, sometimes the scripts are loaded correctly but not always.
<script>
$(document).on('turbolinks:load', function() {
$.when(
// Required libs to token and fraud detection
$.getScript("https://openpay.s3.amazonaws.com/openpay.v1.min.js"),
$.getScript("https://openpay.s3.amazonaws.com/openpay-data.v1.min.js"),
$.Deferred(function(deferred){
$(deferred.resolve);
})
).done(function(){
OpenPay.setId('123');
... more code ...
});
</script>
I'm getting:
How can I do that? I'm using rails 5

Related

Script loading before jQuery

I have a script in my custom meta-boxes and wish to use jQuery, the problem is that the admin page loads my script before it loads jQuery, rendering my script useless, when I inspect the page it looks like this:
jQuery(document).ready(function($) {
// use $
});
<!DOCTYPE html>
and then the rest of the document loads, with header and all that sweet jazz. Is there anyway I can get my <script>jquery here</script> load AFTER my jQuery gets loaded?
you have to insert your script into this way:
function load_custom_scripts()
{
wp_enqueue_script('custom_script', 'COMPLETE_PATH_TO_YOUR_SCRIPT');
}
do_action ( 'admin_enqueue_scripts', 'load_custom_scripts' );
I suggest you to put all of your custom scripts in a separate JS file and then load to the WP.
Right, you cannot use jQuery until it has loaded..
But you can use plain JS:
window.addEventListener('load', function() {
// $ should be available
}, false);

Modernizr.load()/yepnope : Error when loading JQuery before JS plugins

I'm using Modernizr to load all of my JS and CSS scripts in a specific order with callbacks functions to manage the dependences. But I meet a problem with the loading of Bootstrap witch need JQuery. I have 3 levels of loading :
1) JQuery lib
2) scripts using JQuery but not needing that the document is loaded
3) scripts using JQuery AND needing document loaded
I get the following error in Firbug :
TypeError: l is not a function bootstrap.min.js (ligne 4)
It seems that JQuery does not have time to load before Bootstrap.
Does anybody have an idea please? (to resolve this problem or to purpose another solution to make the same thing) Thanks for your help.
The code in head :
<script type="text/javascript" src="js/modernizr-2.6.1.min.js"></script>
<script type="text/javascript">
Modernizr.load([{
load: 'http://code.jquery.com/jquery-1.10.2.min.js',
complete: function(){
Modernizr.load([
//scripts using JQuery but not needing that the document is loaded
'bootstrap/js/bootstrap.min.js',
'js/plugins/respond/respond.min.js',
'js/plugins/jquery-ui/jquery-ui-1.8.23.custom.min.js',
'js/plugins/easing/jquery.easing.1.3.js',
'js/plugins/parallax/js/jquery.stellar.min.js'
]);
$(function(){
//scripts using JQuery AND needing document loaded
Modernizr.load([
{
test : Modernizr.touch,
yep : 'js/plugins/toucheeffect/toucheffects.js'
},{
test : $('.camera_wrap').length,
yep : {
'js':'js/plugins/camera/camera.min.js',
'css':'js/plugins/camera/css/camera.css'
},
complete : {
'js': function(){
$('.camera_wrap').camera();
console.log("plugin loaded!");
}
}
}
]);
});
}
}]);
</script>
[EDIT] alert(jQuery) at the beginning of the first callback function is OK so I don't understand why Bootrstarp don't run correctly...

How to wait until DOM has loaded before adding script tags to <head>?

I'm implementing this Developr theme from themeforest into a Meteor app.
I'm currently accomplishing this by placing the javascripts in question to /public and appending them using jQuery:
Meteor.startup(function() {
$('head').append('<script src="/template_stuff.js"></script>');
// .. all 7 scripts or so
});
If the required scripts are placed in /client/js/, it appears that they either run too early or before the DOM is done loading. If they are placed directly in the header of the main html file, they seem to bug out the same way.
Am I missing something here - is there a more elegant way to make the scripts load after DOM has loaded?
There are several methods for waiting until the DOM has loaded to inject your scripts:
Meteor.startup (as you illustrated)
jQuery's document ready: $(function () { ... })
script tag at the bottom of your layout template
Regarding elegance, I use a handlebars helper as it allows me to consolidate all 'after body' code in one place. Then use jQuery's document ready as needed.
For example,
// in client/handlebars.js
Handlebars.registerHelper('afterBody', function(name, options) {
function isMobileSafari() {
return navigator.userAgent.match(/(iPod|iPhone|iPad)/) &&
navigator.userAgent.match(/AppleWebKit/)
}
if (isMobileSafari()) {
$(function () {
FastClick.attach(document.body)
})
}
//// load scripts however you want...
// $(function () {
// $.getScript as Daniel suggests
// $('body').append as you have
// pure js: document.createElement('script')
// })
})
// in client/main.html (using mini-pages router)
<template name="layout_no_header">
{{{yield}}}
{{afterBody}}
</template>
<template name="layout">
{{> header}}
{{{yield}}}
{{afterBody}}
</template>
Use jQuery getScript()
(function ($) {
$.getScript("/template_stuff.js");
})(jQuery);
I think you might have a different problem. It sounds like the 3rd party code is being wrapped in a closure and is not working correctly. Try and place them inside the client/compatibility folder. This will prevent it from being wrapped in a closure, which can solve 3rd party problems. Be sure the load order inside of here is correct, it loads files in alphabetical order inside of a folder. (load order)
If that doesn't work, find out where the code is being executed and comment out the call. Then load your html inside of a template, even if it's just a 'page' template with all the html. Create a js file for the template and call the methods in the templates rendered callback.
// Execute this function when myPage template is rendered
Template.myPage.rendered = function() {
stuff.init();
stuff2.run();
};
Note, the to call stuff2, etc.. you'll likely need to have it's script in the compatibility folder so you can reach the namespaces from the template_stuff.js.

Run javascript from external location after jQuery(document).ready()

An external javascript loads like this in a div in the page content:
<script type="text/javascript" src="http://example.com/example.js"></script>
The external script prints a sign up form for newsletter, like this:
document.write("<body>\n<form method=\"post\" action ETC....");
The problem is that the external server is slow and this third party script loads before jQuery(document).ready(), which deleays slideshows facebook plugins etc.
How can I make this script to render at it´s current position in the page content after the entire page has loaded?
(I have tried lot´s of suggested sollutions in different threads, but none worked for me...)
Use $(window).load it will be triggered after all the files/assets being downloaded.
$(window).load(function () {
// run code
});
What you need to do is "inject" the script one the page has loaded:
$(function () {
$('body').append('<script src="example.com/script.js"></script>');
});
This will execute on document ready but it's not a problem since the script will be loaded asynchronously.
<body onload="RunScript();">
function RunScript()
{
document.write("<body>\n<form method=\"post\" action ETC....");
}
or
document.onload=function ...

loading scripts when pjax do its job

i have project in MVC CodeIgniter framework and i have for each view its javascripts, and it is on end of that view.
Now when pjax load that page, it should load script, but it doesnt.
Script tag is there, but its not loaded, need somehow to load it on pjax ?
<script>
$(document).ready(function() {
$('body').on('change', '#grad, #adresa', function() {
adresa = getAddress();
marker.codeAddress(adresa);
});
$('#form').validator({message : ''});
.
.
. // more functions
} );
</script>
Any help ?
I'm a little late, but for others finding this through Google:
Scripts loaded in a PJAX request shouldn't be in a .ready wrapper since the document will not trigger the loaded event. The main document stays in place, only a fragment is replaced.
This means that you should init plug-ins and stuff again after the PJAX request has finished. This can get tricky sometimes.
pjax:success would be a great event to listen for to do this.

Categories