Load a function immediately - no access to <body> - javascript

I need to load a function as soon as a page loads, but I am working with a CMS that does not provide me access to the BODY tag. So I am not able to load it on the body, but in the content of the page. Any suggestions on the best way of loading a function in the content of the page?
I prefer to have it in regular Javascript, Jquery has been causing problems with the site as well.

You can use
window.onload = function() {
...
};
As Quentin commented, you can also use addEventListener or attachEvent.

If you don't need to wait until the DOM is ready.
<script> function_call(); </script>
Otherwise bind it to the load event with addEventListener.

Related

Jquery LOAD as alternative or similar to IFRAME

I have jquery to load user messages every 1 second but I would like to implement a solution to the messages load to act, similar as a: <iframe>, <object> or <embed> tags
<script>
setInterval(
function()
{
$('#chat').load('load_chat.php');
}, 1000);
</script>
The problem is as it loads every 1 second I can't just use a iframe of the page, I need to keep using jquery, somebody has a solution?
I tried with:
<script>
setInterval(
function()
{
//$('#chat').load('load_chat.php');
$("#frame").attr("src", "load_chat.php");
}, 1000);
</script>
But this is not what I need, it flash the iframe all the time.
I need to make jquery load method looks like a iframe.
but the problem with using iframe is because I need jquery to refresh the frame every 1 second. some body has an idea of how to make <div id="chat"></div> have a scroll bar as iframe ?
First off all I think this is not the correct way to do this.
Read up on streams, because this type of use case is exactly what they where made for.
Then, if you have your load-chat.php loaded in an iframe, you can use the window send message method to trigger a reloadin the page by jquery.
The downside is, that your iframe should also contain a jquery instance.
Check this -> https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
I solved with the following:
$('#chat').css("overflow-y", "scroll");
If someone has a better alternative it would be appreciated.

Force re-firing of all (scripts / functions) on ajaxed content

tl;dr
I use ajax to fetch new content. The content is fetched and added to the page. However, scripts don't "re-fire" because their calls are outside of the ajaxed div.
The scripts load and fire without any problem on initial page load but not when I add new content via ajax. I get no console errors and there are no issues if I visit the URL directly.
Related:
Forcing Script To Run In AJAX Loaded Page - Relates to one specific script. I want to fix (refire) all scripts including dynamic ones from Cloudflare apps
Using jQuery script with Ajax in Wordpress - Same as above, this relates only to one specific script
ajax loaded content, script is not executing
Intro:
I use Ajaxify WordPress Site(AWS) on a WordPress website.
The plugin lets you select a div by its id and then fetches new content inside that div using ajax
html markup
<html>
<head></head>
<body>
<div id="page">
<header></header>
<main id="ajax"> <!-- This is what I want to ajaxify -->
<div class="container">
main page content
</div>
</main> <!-- end of ajaxfied content -->
<footer></footer>
</div> <!-- #page -->
</body>
</html>
Problem
The plugin works and I get fresh content loaded and styled but there is an issue. Some of my page scripts and function calls are outside of the div that I use ajax on. I have two examples
1- Masonry is loaded and called in the <footer>
<html>
<head></head>
<body>
<div id="page">
<header></header>
<main id="ajax"> <!-- This is what I want to ajaxify -->
<div class="container">
main page content
</div>
</main> <!-- end of ajaxfied content -->
<footer></footer> <!-- Masonry script is loaded and called here -->
</div> <!-- #page -->
</body>
</html>
2- Google maps call is in the <head>
<html>
<head></head> <!-- Google maps is called here -->
<body>
<div id="page">
<header></header>
<main id="ajax"> <!-- This is what I want to ajaxify -->
<div class="container">
main page content
</div>
</main> <!-- end of ajaxfied content -->
<footer></footer>
</div> <!-- #page -->
</body>
</html>
These are just two examples. There are others in other locations. As you can tell, such scripts won't be re-called as the only thing that reloads on the page is <main id="ajax">. While the new content inside <main> is there, some of the scripts required to render it properly are not re-called and so I end up with missing elements / broken layout.
I am not the only one who has faced this problem; a quick look at the plugin's support forum on wordpress.org shows that this issue is common.
Note: I wouldn't try to fix this if the plugin had many other issues. It works for me I just need the scripts to re-fire.
The official response is that it's possible to reload / re-fire scripts by adding the following into the plugin's php files:
$.getScript(rootUrl + 'PATH TO SCRIPT');
Which works. It works well. for example if I add
$.getScript(rootUrl + '/Assets/masonry.js');
Then the masonry function calls get re-fired when the ajaxed content is fetched even if masonry.js is loaded outside of the ajaxed div
I refer you to the plugin's files on github for more clarity on what the fix actually does (I can't make sense of what happens when $.getScript is used)
In summary
The official fix works fine if you have 3-4 scripts that need to be re-fired on ajaxed content.
This does not work for my goal because
it's too rigid and hard-coded
Some of the scripts are added to the page dynamically via Cloudflare apps
A possible solution might involve adding an event mimics the trigger that causes the scripts to fire at the bottom of the ajaxed div
Question:
How do I force all scripts - including dynamically added ones - to re-fire when only a certain part of the page has been reloaded via ajax?
Notes:
I am trying to avoid calling out scripts one by one as that would require knowledge of their calls before hand. I am probably talking way over my head but...
I am trying to mimic the page load and / or document ready events - at which most conditional scripts are fired (correct me if I'm wrong) - at the end of <main> in my html when new ajaxed content is added but without affecting the document when the page is loaded via using the url directly...or any other similar approach.
Just for a bit of context, here is a list of some the event listeners on the page while the plugin is off. I know there are things in there I won't have to trigger. I just added this for reference. Also, please note that this is a sample taken from one of the pages. other pages may differ.
DOMContentLoaded
beforeunload
blur
click
focus
focusin
focusout
hashchange
keydown
keyup
load
message
mousedown
mousemove
mouseout
mouseover
mouseup
mousewheel
orientationchange
readystatechange
resize
scroll
submit
touchscreen
unload
The solution you choose here will have to depend on how the scripts are initialized. There are a couple common possibilities:
The script's actions are evoked immediately upon loading of the script. In this case, the script might look something like this:
(function() {
console.log('Running script...');
})();
The script's actions are evoked in response to some event (such as document ready (JQuery) or window onload (JavaScript) events). In this case, the script might look something like this:
$(window).on('load', function() {
console.log('Running script...');
});
Some options for these two possibilities are considered below.
For scripts that run immediately on loading
One option would be to just remove the <script> elements you want to trigger from the DOM and then reattach them. With JQuery, you could do
$('script').remove().appendTo('html');
Of course, if the above snippet is itself in a <script> tag, then you will create an infinite loop of constantly detaching and re-attaching all the scripts. In addition, there may be some scripts you don't want to re-run. In this case, you can add classes to the scripts to select them either positively or negatively. For instance,
// Positively select scripts with class 'reload-on-ajax'
$('script.reload-on-ajax').remove().appendTo('html');
// Negatively select scripts with class 'no-reload'
$('script').not('no-reload').remove().appendTo('html')
In your case, you would place one of the above snippets in the event handler for AJAX completion. The following example uses a button-click in lieu of an AJAX completion event, but the concept is the same (note that this example doesn't work well within the StackOverflow sandbox, so try loading it as a separate page for the best result):
<html>
<head></head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script class="reload-on-ajax">
console.log('Script after head run.');
</script>
<body>
<button id="reload-scripts-button">Reload Scripts</button>
</body>
<script class="reload-on-ajax">
console.log('Script after body run.');
</script>
<script>
$('#reload-scripts-button').click( () => $('script.reload-on-ajax').remove().appendTo('html') );
</script>
</html>
Note that if the scripts are not inline (e.g. fetched via the src attribute), then they will be reloaded from the server or retrieved from browser cache, depending on the browser and settings. In this case, the best approach is probably to remove all the <script>s that operate on the AJAX-loaded content, and load/run them via something like JQuery's getScript() function from an AJAX completion event handler. This way you will only be loading/running the scripts once at the appropriate time (i.e. after the AJAX content is loaded):
// In AJAX success event handler
$.getScript('script1.js');
$.getScript('script2.js');
A potential problem with both variants of this approach is that asynchronous loading of the script is subject to cross-origin restrictions. So if the scripts are hosted on a different domain and cross-origin requests are not allowed, it won't work.
For scripts that run in response to an event
If the scripts are triggered on window load, then you can just trigger this event:
$(window).trigger('load');
Unfortunately, if the scripts themselves use JQuery's document ready event, then I'm not aware of an easy way to trigger it manually. It's also possible that the scripts run in response to some other event.
Obviously, you can combine the above approaches as necessary. And, as others have mentioned, if there's some initialization functions in the scripts that you could just call, then that's the cleanest way.
If you can identify a global initialising function or code block in your external scripts, you could take a look at the 'ajaxComplete' event. You can put this code in your page head and put the initialising function calls or code blocks inside the ajaxComplete callback.
$(document).ajaxComplete(function(){
module1.init();
$('#my_id').module2_init({
foo : 'bar',
baz : 123
});
});
When the scripts you are talking about don't have such easy-to-use exposed initialising functions, but initialise themselves on scriptload, I think there will be no out of the box method that works for all scripts.
Here's what you can try -
Most of the scripts like masonry or Google Map are set to re-init on window resize. So, if you trigger the resize event after ajax complete, it will help to re-fire those scripts automatically.
Try the following code -
$( document ).ajaxComplete( function() {
$( window ).trigger('resize');
} );
This will force the scripts to re-init once ajax is completed as it will now trigger the resize event after the content is loaded.
Maybe risky, but you should be able to use DOMSubtreeModified on your <main> element for this.
$('#ajaxed').bind('DOMSubtreeModified', function(){
//your reload code
});
Then you should be able to just append all your scripts again in your reload area
var scripts = document.getElementsByTagName('script');
for (var i=0;i<scripts.length;i++){
var src = scripts[i].src;
var sTag = document.createElement('script');
sTag.type = 'text/javascript';
sTag.src = src;
$('head').append(sTag);
}
Another option could be create your own event listener and have the same reload code in it.
$(document).on('ajaxContentLoaded', function(){//same reload code});
Then you could trigger an event in the plugin once the content had been updated.
$(document).trigger('ajaxContentLoaded');
Or possibly a combination of editing the plugin to trigger a listener and adding to your codebase to re-run anything you feel you need to have re-ran off that listener, rather than reload anything.
$(document).on('ajaxContentLoaded', function(){
//Javascript object re-initialization
myObj.init();
//Just a portion of my Javascript?
myObj.somePortion();
});
A solution could be duplicating all the scripts...
$(document).ajaxSuccess((event, xhr, settings) => {
// check if the request is your reload content
if(settings.url !== "myReloadedContentCall") {
return;
}
return window
.setTimeout(rejs, 100)
;
});
function rejs() {
const scripts = $('script[src]');
// or, maybe alls but not child of #ajax
// const scripts = $('*:not(#ajax) script[src]');
Array
.prototype
.forEach
.call(scripts, (script, index) => {
const $script = $(script);
const s = $('<script />', {
src: $script.attr('src')
});
// const s = $script.clone(); // should also work
return s
.insertAfter($script)
.promise()
.then(() => $script.remove()) // finally remove it
;
})
;
}
I had this exact problem when attempting to use ajax to reload a page with browser states and history.js, in wordpress. I enqueued history.js directly, instead of using a plugin to do that for me.
I had tons of JS that needed to be "re-ran" whenever a new page was clicked. To do this, I created a global function in my main javascript file called global_scripts();
Firstly, make sure this JS file is enqueued after everything else, in your footer.php.
That could look something like this:
wp_enqueue_script('ajax_js', 'url/to/file.js', 'google-maps', 1, true);
My javascript that I enqueue is below.
jQuery(document).ready(function($) {
// scripts that need to be called on every page load
window.global_scripts = function(reload) {
// Below are samples of the javascript I ran that I needed to re run.
// This includes lazy image loading, paragraph truncation.
/* I would put your masonry and google maps code in here. */
bLazy = new Blazy({
selector: '.featured-image:not(.no-blazy), .blazy', // all images
offset: 100
});
/* truncate meeeee */
$('.post-wrapper .post-info .dotdotdot').dotdotdot({
watch: 'window'
});
}
// call the method on initial page load (optional)
//global_scripts();
});
I then hooked into the JS that ran whenever a page was loaded with history.js and called global_scripts();
It seems as though the plugin you are using also uses history.js. I haven't tested it with your plugin specifically, but you can try what I posted below (which is what I use in my app).
This would go in the same JS file above.
History.Adapter.bind(window, 'statechange', function() {
global_scripts();
}
My code is a bit more complicated than what is simply pasted above. I actually check the event to determine what content is being loaded, and load specific JS functions based on that. It allows for more control over what gets reloaded.
note: I use window.global_scripts when declaring the function because I have separate JS files that hold this code. You could chose to remove this if they are all in the same.
note2: I realize this answer requires knowing exactly what needs to be reloaded, so it ignores your last note, which asks that this doesn't require such knowledge. It may still help you find your answer though.
Short answer:
It is not possible to this in a generic way. How should your script know which events needs to be fired?
Longer answer:
It is more like a structural question than a programmatic one. Who is responsible for the desired functionality? Lets take masonry as an example:
Masonry.js itself does not listen to any events. You need to create a masonry instance by your own (which is most probably done on domready in your Wordpress plugin). If you enable the resize option it will add a listener to the resize event. But what you actually want is some listener on "DOM content change" (see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver for possible solution). Since masonry.js does not provide such a function you have the following options:
Wait for the implementation (or do it yourself) in masonry.js
Wait for the implementation (or do it yourself) in masonry Wordpress plugin.
Add the functionality somewhere else (your template, your ajax plugin, etc.)
4.
As you can see every option includes some work to be done and this work needs to be done for every script you want to listen to your AJAX invoked DOM changes.

Javascript From Console - Load a Few Pages, Then Run Function Per Page Load [duplicate]

I'd like to be able to call a jquery function once window.location has completed loading a URL. Is this possible? I can't seem to find anything online about this.
for instance:
if(parseInt(msg.status)==1) {
window.location=msg.txt;
alert("This URL has finished loading")
}
Thanks,
-Paul
You can either use window.onload of the destination page (if you have access to modify the code of that page), or you can use window.onunload to have the alert be launched when unloading the current page. You cannot execute code on the current page after the new page has been loaded.
Yes.
This page demonstrates onload/onunload behavior.
<html>
<head>
<script>
window.doUnload = function(){
alert("Here!");
}
window.doLoad = function(){
window.location="http://www.google.com";
}
</script>
</head>
<body onload="doLoad();" onunload="doUnload();"></body>
</html>
After a user logs in for the first time I need to load my index page to initialize everything but then need to forward them to another page for profile completion.
use window.location to redirect the user to your index, adding a query parameter (something like window.location=index.php?firstLogin=true ) and on your index redirect (using javascipt http 300, header() or whatever you are using) to the profile page after it ends loading if the parameter is set
Iframe
One (ugly) method you could use is to instead of using window.location, clearing the body, adding an iframe with the relevant path and listening to its onload function.
After that you can run code inside the iframe as long as it's not cross-site scripting.
I use this method to perform small automated scripts, that can't really on third-party plugins.
Ajax
Another method might be using ajax to load the page/body content. Then replacing your body with the newly loaded body and start executing the next functions.

Check if iFrame is loaded. ONE time. Jquery

I know there is many of possiblites when it comes to check if an iFrame content has been loaded. Although, is there anyway to limit it?
Example, if I have an iframe, and I need to check if everything has loaded, I can use the load() function. Although, if I click a NEW link inside the iframe, it will run the load() function again.
What I wish to know, is there any way to do, so jquery only checks the FIRST time the iFrame content has been loaded?
I have tried everything, nothing works.
Use jquery .one, it does the unbind work for you.
$('#iframe').one('load', function() {
});
Example fiddle.
You can unset the load callback again once it gets called.
$('#iframe').load(function() {
// do things which are awesome
$('#iframe').unbind('load');
});

Has window.onload fired yet?

I have a script that will be inserted into an unknown page at an unknown time. Is it possible to tell from this script if window.onload has fired yet?
I have no control over the host page. I can't add any markup or scripts to it. All I know is that my script will be inserted into the page at some point. It could be before window.onload or after; and I need to detect which side of that event I'm on.
Updated Answer:
Look at this site. He uses a trick by seeing if the last element of document.getElementsByTagName("*") is defined or not. It seems to work in Opera and IE.
Original Answer:
You can't check, but you can do:
window.setTimeout(function () {
// do your stuff
}, 0);
That will do your stuff definitely after the page has loaded.
jQuery's ready() will queue a function to be fired when the document is loaded, or fire immediately if the document is already loaded:
$(document).ready(function() {
//your code here
});
Just be sure jQuery is included before your script block. If you can't include any script resources directly, you can always copy the body of jQuery-min in your script itself.

Categories

Resources