jQuery script only working if it's above a function - javascript

I am using Bootstrap as my template, and Laravel as my framework. As suggested within the examples, you should load your jQuery script at the bottom of the page - to speed up the loading.
Within my application, I have this function that checks if an alert exists in the session, and if so, show it:
$(document).ready(function() {
toastr.options = {
"closeButton": false
};
toastr. {
{
Session::get('flash_notification.level')
}
}('{{ Session::get('
flash_notification.message ') }}')
});
This is shown above where I load the jQuery script:
#if (Session::has('flash_notification.message'))
<script>
The above script is loaded here.
</script>
#endif
#yield('content')
</div>
<!-- Scripts -->
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
In order to get this working, I need to declare my jQuery file in the header of the template, but I know this isn't best practice. I initially thought that by using the $(document).ready() method, it would resolve this, but it doesn't.
Any help would be greatly appreciated.

It is best to put the script calls in the footer so they are loaded last. This means that any other JS you write will need to be below them. You could add your other JS to another file which is included after the jQuery load.
If you cannot, you could add it to the header and add the defer attribute to the script tag to defer it's loading.
Option 1 should be preferred though.

Related

Jquery script stopping JS script from working

I have 4 JS scripts and 1 JQuery script src at the bottom of my HTML page. When I include the JQuery script, though, the code in JS script delayed.js only works for a second, then stops. All the other JS scripts work. How can I fix this?
I have tried:
changing the order of the scripts on the HTML page
changing the JS code in delayed.js into JQuery
moving the JS code in delayed.js into another JS script in which JS is working
Changing the JQuery reference (e.g. from Google APIs)
Here's the code at the bottom of my HTML page:
<script defer src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script defer src="assets/js/skel.min.js"></script>
<script defer src="assets/js/util.js"></script>
<script defer src="assets/js/main.js"></script>
<script defer src="assets/js/delayed.js"></script>
Here's the code in delayed.js. It's for changing the style of the nav item according to the specific page you're on, so as a user the page you're currently on is always clear.
if (document.body.classList.contains('index')){
document.getElementById('nav-wwd').classList.add('selected');
}
if (document.body.classList.contains('approach')){
document.getElementById('nav-oa').classList.add('selected');
}
if (document.body.classList.contains('about')){
document.getElementById('nav-wwa').classList.add('selected');
}
if (document.body.classList.contains('insights')){
document.getElementById('nav-oi').classList.add('selected');
}
if (document.body.classList.contains('contactus')){
document.getElementById('nav-c').classList.add('selected');
}
Thanks in advance for any advice you can give.

Magnific Popup install/initialization

I'm very new to all this and having trouble installing it to my my backend code. Where does it go? Below my footer with all my JS?
Like, what does it mean by:
Popup initialization code should be executed after document ready?
Could someone please let me know if this is correct:
$(document).ready(function() {
$('.image-link').magnificPopup({
type:'image'
});
});
I've put this inside a script tag.
Which lies underneath my closing footer but just doesn't seem to work.
yes, put all necessary css and js files first. js files can be included in header or footer. It doesn't matter (footer is preferred location for loading js nowadays). However, don't call the magnificPopup() function before loading necessary js files. After all are loaded you can use your code in docready like you mentioned.
<!-- jQuery 1.7.2+ or Zepto.js 1.0+ -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- Magnific Popup core JS file -->
<script src="FOLDER_WHERE_YOU_KEPT_THIS_JS_FILE/jquery.magnific-popup.js"></script>
<script>
$(document).ready(function() {
$('.image-link').magnificPopup({
type:'image'
});
});
</script>
This should work if there no other js conflict and you created the html correctly like mentioned in the doc. Let me know if there is more confusion or if still you could not make it work...

Loading jquery in the last position

I offen heard that loading jquery as last element is a good idea because this way a web page loads faster. At the same time I have a script in the header which shows error:
$(document).ready(function () {// Uncaught ReferenceError: $ is not defined
...
}
Should I move jquery loader before the script or I need to change this script some way?
Your concrete issue stems from the fact that you execute statements that use jQuery (i.e. they execute $, which is a function in the jQuery library, also called "the jQuery function" because jQuery is an alias) before it is loaded.
True, it is typically recommended to load scripts last, but that still means the scripts have to be loaded in the correct order, with usually jQuery before your own scripts using jQuery.
If you really want to load your own scripts before jQuery for some reason, you need to defer its execution and have a third helper script to run it, e.g.:
// script.js
(function() {
function myLibraryMainFn() {
$('div').text('simulating work, utilizing jQuery');
}
window.myNamespace = {
run: function() {
myLibraryMainFn()
}
};
}());
<!DOCTYPE html>
<html>
<body>
<div></div>
<script src="script.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
// Run your script now:
window.myNamespace.run();
</script>
</body>
</html>
Always refer library file first(in your case jQuery), then use it next..For page load and performance add it before body end tags of your HTML

jQuery plugins conflict and script declaration order

I'm new to web development, and was having issues with two plug-ins. I already found a workaround to solve it, but I'm not convinced at all about what I did, so I ask you guys if you can enlighten me on what is this about.
The page in question uses SlimScroll and DataTables plugins. At first, I had an HTML file like this one.
<body>
<!-- STUFF -->
<!-- SCRIPTS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="plugins/slimScroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<script src="plugins/DataTables/datatables.min.js" type="text/javascript"></script>
<script src="assets/scripts/tablas.js" type="text/javascript"></script>
<script src="assets/scripts/general.js" type="text/javascript"></script>
At the bottom, general.js is used to handle click events and other stuff, and tablas.js has the code that picks up a file with data and displays it in DataTables. The relevant code from general.js:
$(document).ready(function() {
$('#contenedor-menu').slimScroll({
height: '100%'
});});
And the code for tablas.js:
$(document).ready(function() {
$('#tablita').DataTable( {
"ajax": 'data/COut2.txt',
} );});
With this structure, when I load the page, SlimScroll fails with the message in the console: "TypeError: $(...).slimScroll is not a function"
Then after touching around, I switched the order of the scripts in the HTML file. I put datatables first and then slimscroll.
<script src="plugins/DataTables/datatables.min.js" type="text/javascript"></script>
<script src="plugins/slimScroll/jquery.slimscroll.min.js" type="text/javascript"></script>
And now it works ok, with no errors.
Could somebody please explain to me what's going on?
Thanks in advance!
The use of multiple $(document).ready(function() { } is the main cause of this issue. There should be only one Document Ready event handler.
You may try using the pageLoad() function or onLoad() events
Not positive but it is usually best practice to put the scripts you absolutely need before everything else in the head. This is so that the content of the page does not finish loading until all the dependencies have been loaded first.
By reordering your scripts you may have a solution that will only work some of the time.
Put all the scripts you need to load in the head and your general.js script at the end of your body element.

Addthis is Undefined when I use addthis, When I load page by Ajax

I'm try to show 'addthis sharing' buttons when make ajax call. at the first call by ajax, buttons does not show, but when I reload whole page everything is OK, buttons is right place.
I searched a lots of fixes but no one works for me.
one of them is addthis.toolbox(); or window.addthis but when I use word addthis insde JavaScript tag, browser debugger writes error 'addthis is undefined'.
please give me smart advice what's happen and how can I fix it ?
Code (it's a partial view which load from ajax Call):
<script type="text/javascript" src="http://s7.addthis.com/js/300/addthis_widget.js#pubid=ra-xxxxx" async="async"></script>
<div class="addthis_sharing_toolbox"></div>
<script>
addthis.toolbox(); // addthis - is undefined
</script>
I have fixed this problem.
In my project I have 3 View level
_layout
View
_partialview
I had addthis Js reference and button's Div inside the _partialView.
But when I move Js reference to View and change Url(add - &async=1) it works fine and now 'addthis' - is defined (till here is undefined).
Hare is full example:
View:
<script type="text/javascript" src="http://s7.addthis.com/js/300/addthis_widget.js#pubid=ra-'yourPubId'&async=1"></script>
//Some Code
_partialView:
//Some Code
<div class="addthis_sharing_toolbox"></div>
<script>
$(function() {
addthis.init();
addthis.layers.refresh();
});
</script>
Good luck, everyone can use this perfect plugin 'addthis' when you load page by Ajax.
The async version of the addthis_widget.js script you're using was intended to be used for the newer dashboard tools, as the call to addthis.toolbox() is undefined because AddThis hasn't fully loaded yet. If you remove async="async" from the script, it should work.
Alternatively, you could add the async attribute this way:
<script src="http://s7.addthis.com/js/300/addthis_widget.js#pubid=ra-xxxxx&async=1" type="text/javascript">
Then before you call addthis.toolbox(), make sure you call addthis.init().
https://www.addthis.com/blog/2013/05/07/a-brief-history-of-using-addthis-dynamically/
-Matt
AddThis Support

Categories