How can I reliably run a jquery script after page load - javascript

I'm attempting to get some jquery code to run after a sharepoint page loads, the code being:
$(".ms-commentcollapse-icon").click();
I've been using the following to load the code after the page loads, but it does not seem to be very reliable (it will work sometimes and other times it wont):
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(window).load(function () {
$(".ms-commentcollapse-icon").click();
});
</script>
are there any other good methods for achieving this? I'm not sure what's going on, sharepoint could be at fault, but I figured I would try fiddling around with the script a bit more first.

You could use an auto-executing function:
<script type="text/javascript">
(function () {
$(".ms-commentcollapse-icon").click();
} ());
</script>

If this is SharePoint 2010 or above, you can use ExecuteOrDelayUntilScriptLoaded(yourfunction,"SP.JS") to keep your code from firing until after the SP.JS library has loaded (or you can put any other library in the second parameter for a similar effect).
If this is in a web part and you don't want it to execute until other web parts on the page are fully loaded, make sure the web part containing the script is below the other web parts.
As a last resort, you could execute it on a delay using setTimeout or setInterval, but that's ugly.

You can prevent the default behaviour by using e.preventDefault(); within the function.
<script type="text/javascript">
$(".ms-commentcollapse-icon").click(function(e) {
// We're going to stop the default behavior
e.preventDefault();
//some code here
});
</script>

Related

The "document.ready()" function not firing on Chrome Mobile (android)

I have jQuery-2.1.4.min.js called before the tag, but when I write something like:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
alert('hi, world.');
});
</script>
On my PC it is fired of course, but on ten different Android devices it just does not. This is purely HTML/CSS/jQuery rendered site (no phonegap, or anything).
My goal was to have a button do ajax request after it's being tapped, but I can't even test that, because the .ready() function is not firing at all on mobile chrome.
The jQuery is being served from the official CDN, any help would be very much appreciated.
Tried both:
$(function() {
alert('hi, world.');
});
And
jQuery(document).ready(function() {
alert('hi, world.');
});
Same thing.
As suggested I also tried:
window.onload = function()
{
if (window.jQuery)
{
alert('jQuery is loaded');
}
else
{
alert('jQuery is not loaded');
}
}
And it alerts 'jQuery is loaded'.
As per jQuery docs it says: "Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute" - which would mean that DOM is not ready for JavaScript code to execute? But when I try like:
<script type="text/javascript">
alert('hi world');
</script>
It executes on mobile Chrome.
Okay, after extensive investigation it seems that JS breaks on mobile chrome if you have document.ready() function twice, I had one in my core.js file and one in-line on the page.
It works okay on PC (all browsers), but on mobile it works up to the point of second ready() call and breaks all JS after that.
Hopefully this saves some time to others in the future.
JS breaks on mobile view becouse same js use multiple time in file. Check and remove redundancy.

jQuery loaded async and ready function not working

In order to optimize the load of my document, I use to load jQuery async like that
<script async type="text/javascript" src="js/jquery-1.12.3.min.js"></script>
Then I call a script using jQuery :
<script type="text/javascript">
jQuery(document).ready(function() {
App.init();
OwlCarousel.initOwlCarousel();
FancyBox.initFancybox();
StyleSwitcher.initStyleSwitcher();
});
</script>
It returns me that jquery is not defined.
I don't know what should I use, I though that .readyfunction would wait until all document is loaded before calling it.
The same for Bootstrap library, It tells me that jQuery is not defined.
I've tried to ask the script to be loaded at the end, but it still does not work properly.
Since jquery script is loaded asynchronously, jquery is not loaded on the moment your script is executing. So you need to wait for it to load by subscribing on load event like this:
<script async id="jquery" type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
Then listen for a load event on this element
<script type="text/javascript">
document.getElementById('jquery').addEventListener('load', function () {
App.init();
OwlCarousel.initOwlCarousel();
FancyBox.initFancybox();
StyleSwitcher.initStyleSwitcher();
});
</script>
But I don't know why someone wants to do things like this.
To optimize page loading speed it is better to put all you javascript at the end of the body, so content will be loaded first, and scripts won't delay page rendering event if it's synchronously loaded.
Edit: I agree with comment and consider previous paragraph not the best way of loading jQuery to the page
Question Script Tag - async & defer has good answer to your problem.
In a nutshell you cannot load jQuery, or other library, asyncronously when some other script depends on it without some additional asyncronous handling for executing the scripts depending on the library.
That is my solution:
<script async type="text/javascript" src="path_to_jquery" id="jquery_script_tag">
</script>
<script>
if ( !('jQuery' in window) )
{
window.jQueryQueue = [];
//define temporary jQuery function
window.jQuery = function(){
//just save function parameters to queue
jQueryQueue.push( arguments );
}
document.getElementById('jquery_script_tag').addEventListener('load', function(){
//call jQuery with parameters saved in queue, after it loaded
for ( var i in jQueryQueue )
jQuery.apply( document, jQueryQueue[i] );
});
}
</script>
This code defines a temporary jQuery function if it is yet not defined. The function saves all jQuery function calls to queue while the real jQuery has not yet loaded (instead of calling undefined jQuery function). And when jQuery has loaded, it calls the jQuery functions in the queue with the same parameters as called before.
jQuery, and all components that depend on jQuery (including Bootstrap), depend on hooking the DOMContentLoaded event to set up events.
This means jQuery (and anything that uses $(function() {...})) must be downloaded before DOMContentLoaded fires, or it never hooks up its events.
In turn, that means <script async ... will be unreliable, breaking whenever jQuery takes longer to download than the page content does.
Unfortunately <script defer ... doesn't work either thanks to jQuery trying to fire as soon as the document.readyState === "interactive".
You can load content and then load jQuery by putting the <script> at the end of the <body> but this will result in a noticeable pause between the page appearing and any of the jQuery firing - users won't be able to click on anything, visual components won't appear, and so on.
This way works just fine:
<script charset="utf-8" type="text/javascript">
var intervalID = window.setInterval(function(){
if(window.jQuery){
clearInterval(intervalID);
console.log('Loaded');
/* Your code here */
}
},1000);
</script>
You Used Async Loading When You Try Access Jquery It Not Loaded By Browser You Can Access Jquery After Page Loading Is Complete .
Load Jquery Normally To Fix Your Problem .

What Could be Breaking scrollTo?

On this page:
http://alien.devprose.com/screenfad
I'm attempting to have it scroll to a specific position using javascript when the page is loaded. For example purposes I have this code in the head:
<script type="text/javascript">
window.scrollTo(300,300);
</script>
However, nothing is happening. Any ideas?
It appears that you have jQuery, so the code should be in $(document).ready() like so:
<script type="text/javascript">
$(document).ready(function() { window.scrollTo(300,300); });
</script>
This way, when the window is done loading it will scroll.
You can't call window.scrollTo() until after the document has loaded. Scripts in the HTML (including both in the head and in the body) are executed before that. This StackOverflow question should explain the best ways to run scripts after it's finished loading. In summary:
window.onload = function() { window.scrollTo(300,300); };

Long delay when using Modernizr/yepnope

I'm starting to use Modernizr for my front-end projects these days and just realized something that bugs me.
(Demo link after code snippets)
But first, here's what's before my <body>:
<script src="js/vendor/modernizr.custom.js" type="text/javascript"></script>
<script src="js/loader.min.js" type="text/javascript"></script>
And here's my loader script (removed some lines for brevity):
Modernizr.load([
// jQuery
{
load: '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js',
complete: function () {
if (!window.jQuery) {
Modernizr.load('js/vendor/jquery-1.11.1.min.js');
}
}
}
// Slick (slideshow)
,{
load: '//cdn.jsdelivr.net/jquery.slick/1.3.9/slick.min.js',
complete: function() {
if (!window.jQuery.fn.slick) {
Modernizr.load('slick/slick.min.js');
}
}
}
// Main script
,'js/script.min.js'
]);
Demo link: http://toki-woki.net/lab/transbal/
I can see the page load and, almost a second after that, my slideshow initializer (wrapped in a $() call) kicks in. That delay is fairly long and unaesthetic, which is what I want to fix.
I've looked at the Network tab in Chrome and see my Modernizr-loaded scripts are first loaded as images (thus, not executing) and then added as script tags and, eventually, executing. That would explain the delay, because jQuery would be executed late (after the DOMContentLoaded event) and the $() call would fire after that.
Some questions:
Is that how Modernizr/yepnope works?
Is it possible to reduce that delay?
What event is used by Modernizr/yepnope to determine when to inject script tags? Looks like it's load but that seems like a strange choice to me...
I've tried not using Modernizr.load at all and reference my script just before the </body> tag and it works perfectly (no slideshow size jumping) but it is harder and heavier to maintain...
Got tips?
Thanks!

How to add Javascript code using jQuery and setTimeout()

I have some tracking code that the provider (WebTraxs) says should be placed at the bottom of the tag. The problem is that this same code is causing everything on the page (including my jQuery code) to run AFTER the WebTraxs is executed. This execution sometimes takes long enough where images rollovers, etc aren't working because the user is mousing over images before WebTraxs has finished.
Therefore, I'm trying to add the needed tags (from WebTraxs) to the body after the page is loading in the document ready handler, using the following:
setTimeout(function(){
var daScript = '<script language="JavaScript" type="text/javascript" src="/Scripts/webtraxs.js" />';
var daOtherScript = '<noscript><img alt="" src="http://db2.webtraxs.com/webtraxs.php?id=company&st=img" />';
$('body').append(daScript);
$('body').append(daOtherScript);
},
5000);
I have two problems with the above:
In Firefox, after 5 seconds, it page goes completely blank.
In IE, there's no errors thrown, but normally you can see the WebTraxs code trying to load a tracking image in the status bar. This is not occurring with the above code.
Is there a better way to accomplish my objective here? I'm basically just trying to make sure the WebTraxs code is executed AFTER the document ready handler is executed.
Why don't you use the .getScript function:
setTimeout(function(){
$.getScript("http://path.to/Scripts/webtraxs.js");
},
5000);
What it's really curious about your code is that you add a <noscript> tag using JavaScript... it does not make any sense. If the user does not have JavaScript the setTimeout won't be fired, thus it <noscript> content won't be displayed.
I'm basically just trying to make sure the WebTraxs code is executed AFTER the document ready handler is executed.
In that case, you just have to do this:
$(document).ready(function(){
$.getScript("http://path.to/Scripts/webtraxs.js");
});
You don't have to use jQuery's DOMReady event handler. The reason people use DOMReady is that it allows the full DOM to load before firing up scripts that manipulate the page. If you call your scripts too early, parts of your page may not be accessible -- for example, if you call them before <div id="footer">...</div>, they won't be able to see $('div#footer') because it's not been pulled into the DOM yet. And that's great, except that your DOMReady methods will always execute after any in-page scripts have executed first. That's why your webtrax code is getting executed first.
But you can get the same benefits of DOMReady and still control the order of execution by calling your page scripts at the end of your document, when there's nothing left but HTML closing tags. They will be executed in the order they appear.
So try this instead:
<html>
<head>
<script type="text/javascript" src="myPageScripts.js"></script>
</head>
<body>
<div id="pagesection1"></div>
<div id="pagesection2"></div>
<div id="pagesection3"></div>
<!--NO MORE CONTENT BELOW THIS LINE-->
<script type="text/javascript">//<![CDATA[
runMyPageInitializerScripts();
//]]></script>
<script language="JavaScript" type="text/javascript" src="/Scripts/webtraxs.js" ></script>
</body>
</html>
In this script, runMyPageInitializerScripts() would still have complete access to #pagesection1, pagesection2 and pagesection3, but would not see the final script tag. So the page isn't in exactly the same condition as when DOMReady is fired, but for most scripts usually there is no downside.
<script> tags cannot use a shortcut like <script/>.
You have to use <script></script>
Anyways, I don't understand where the difference is on executing those scripts on DOMready or after a specific amount of time. If it blocks the UI it will do the same after 5 seconds no?
You are missing the closing </script> and </noscript> tags.
If you want to keep the <script> tag you may need to escape it (not sure if this persists on newest browsers, but as far as i remember you can't have <script> tags inside a script tag), take old google analytics code as example:
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
Splitting the script tag also works:
document.write("<scr"+"ipt src='somescript.js'></sc"+"ript>");
But since you're using jQuery, .getScript() is your best option.

Categories

Resources