Run a javascript function on script load - javascript

I am using jQuery. I keep all of my function definitions wrapped in the $(document).ready event in application.js. I have a function from it that I would like to call somewhere in the body of the page I am working on.
I was wondering if there is some alternative to the .ready event that will work on a script load. Ideally I would like to do something like: $('application.js').ready( call function );
In the jQuery documentation it only mentions the $(document).ready call but I was wondering if this can be altered or if there is some plain javascript alternative.

I think you’re looking for $.getScript. This jQuery function loads a JavaScript file from the server using a GET HTTP request and executes it. You can specify a callback function, to be executed after the script itself has been executed.
$.getScript('foo.js', function() {
alert('foo.js was loaded, do something cool now');
});

I am curious about this myself, but instinct would tell me you'd want to wait for the document to finish loading before running any javascript.

Related

execute code in script element after external js file loaded

That's gonna be an abstract question so no code example involved here. Hope you and I saty on the same page till the end of this post ^^"
In my index.html I have element defined async and defer both true.
Additionally, And right after that script element (DOM wise), I have element where I call function exists in the external js file.
unfortunately error undefined thrown over the function. I geuss because the js file ain't fully downloaded while the function in the second script executed.
tnx for all answears. stackoverflow do you magic...
Why don't you move your second script in the callback of your first script ? so when the first one loads and succeeds, the second one is executed.
And it will be helpful if you share your code, it depends on what the scripts actually do.

Find out what js file was loaded, but not used

Is there a way to know what js files was loaded in html, but not used? Let's say I load on a HTML page jQuery, jQuery Tabs, jQuery DatePicker libs, but on that page I use none o them, except jQuery. Is there a way to find out what js files where used ( executed )?
Short answer - No.
Long answer:
Since the files are referenced in the page itself, all scripts would be loaded, executed and it's code(global variables and functions - $ for example) exposed.
The only way to check if a certain part of a script is executed, is to observe the actors or -in other words- the calling code and the called code.
For example:
function callingFunction() {
console.log('I will call this code!');
calledFunction();
}
function calledFunction() {
/// <summary>
/// Lets say this function is added in a external file
/// </summary>
console.log('My code was called!');
}
onDemand scriptloading
A good aproach would be to load your libraries only when needed. jQuery's $.getScript is doing a great job here. If you reference your libraries like this, you can check the currently loaded ones via the network panel.
Update
Chrome 59 now supports Code coverage which does something similar.
Check it out
https://developers.google.com/web/updates/2017/04/devtools-release-notes#coverage
No not really. When you include all files, all javascript code in that file is loaded. If you want to load the js file at the moment you use a function in it, you can check if the plugin is available. If it isn't available then include the file.
E.g.:
if(jQuery().datepicker) {
//Include datepicker here
}
No cause when you include any js into your page it gets loaded,
though you can check what is getting run when you interact with things using thne chrome event listeners tab.
That's the closest you are gonna get
I don't think there is an easy way to do what you want. If the purpose is to do lazy loading, prefer use a library like require

How to use a JavaScript loader like head.js or labjs in Magento

Off the bat Magento comes with more than half a dozen JavaScript libraries which do not help with the already cumbersome load times. Has anybody been able to successfully use a script loader like head.js or labjs with Magento so that they can load asynchronously? I have been trying but can't get it to work.
Seems as though the in-line scripts on the pages are firing before the libraries are loaded. I know that head.js has a function like head.ready to tell a script to execute , but there are so many in-line scripts it is not practical to add this to every occurrence in the whole site.
Regarding the inline scripts, there is a programmatic solution.
You could write an Observer that binds to the core_block_abstract_to_html_after or controller_action_layout_render_before Events which fire immediately prior to outputting the rendered HTML. In your Observer, you could use a preg_replace to insert a head.ready statement immediately after each <script> tag.
It would add a fraction more to the render time, but I suspect it would be less than the latency of downloading the libraries. And if you're using full page caching, then the function would only be called once.
You could use the inbuilt Magento Profiler to test the impact. Worth a try at least.
HTH,
JD
well, i use jquery for this. and it works great.
All you have to do is to make an ajax request that returns the script and then evaluate the script using eval. You can write your own function for this, but jquery already has some nice approaches.
For single scripts, the $.getScript function works well. It's basically an extension of the $.ajax function that specifies that you are requesting a script. the syntax is like this :
$.getScript('my_script_url',function(){
// do whatever needs to be done after the script loads
alert('my script was asynchroniously loaded');
});
If you have more scripts that you want to add through ajax, jquery has a neet way of doing this :
$.when(
$.getScript("/script_1.js"),
$.getScript("/script_2.js"),
$.getScript("/script_3.js")
// ...
//$.getScript("/script_n.js")
).then(
// on succes
function(){
alert('good to go!');
},
// on failure
function(){
alert('loading failed. one or more scripts encountered a problem :(');
}
);
All loaders of this nature are going to require some modification to every script on your site. I know--I just implemented LABjs on a system which, when I grepped, showed over 400 files with some sort of script tag!!

I have an issue with inline vs included Javascript

I am relatively new to JavaScript and am trying to understand how to use it correctly.
If I wrap JavaScript code in an anonymous function to avoid making variables public the functions within the JavaScript are not available from within the html that includes the JavaScript.
On initially loading the page the JavaScript loads and is executed but on subsequent reloads of the page the JavaScript code does not go through the execution process again. Specifically there is an ajax call using httprequest to get that from a PHP file and passes the returned data to a callback function that in onsuccess processes the data, if I could call the function that does the httprequest from within the html in a
<script type="text/javascript" ></script>
block on each page load I'd be all set - as it is I have to inject the entire JavaScript code into that block to get it to work on page load, hoping someone can educate me.
If you aren't using a javascript framework, I strongly suggest it. I use MooTools, but there are many others that are very solid (Prototype, YUI, jQuery, etc). These include methods for attaching functionality to the DomReady event. The problem with:
window.onload = function(){...};
is that you can only ever have one function attached to that event (subsequent assignments will overwrite this one).
Frameworks provide more appropriate methods for doing this. For example, in MooTools:
window.addEvent('domready', function(){...});
Finally, there are other ways to avoid polluting the global namespace. Just namespacing your own code (mySite.foo = function...) will help you avoid any potential conflicts.
One more thing. I'm not 100% sure from your comment that the problem you have is specific to the page load event. Are you saying that the code needs to be executed when the ajax returns as well? Please edit your question if this is the case.
I'd suggest just doing window.onload:
<script type="text/javascript">
(function() {
var private = "private var";
window.onload = function() {
console.log(private);
}
})();
</script>
On initially loading the page the js loads and is executed but on subsequent reloads of the page the js code does not go through the execution process again
I'm not sure I understand your problem exactly, since the JS should execute every time, no matter if it's an include, or inline script. But I'm wondering if your problem somehow relates to browser caching. There may be two separate points of caching issues:
Your javascript include is being cached, and you are attempting to serve dynamically generated or recently edited javascript from this include.
Your ajax request is being cached.
You should be able to avoid caching by setting response headers on the server.
Also, this page describes another way to get around caching issues from ajax requests.
It might be best not to wrap everything in an anonymous function and just hope that it is executed. You could name the function, and put its name in the body tag's onload handler. This should ensure that it's run each time the page is loaded.
Depends what you want to do, but to avoid polluting the global namespace, you could attach your code to the element you care about.
e.g.
<div id="special">Hello World!</div>
<script>
(function(){
var foo = document.getElementById('special');
foo.mySpecialMethod = function(otherID, newData){
var bar = document.getElementById(otherID);
bar.innerHTML = newData;
};
//do some ajax... set callback to call "special" method above...
doAJAX(url, 'get', foo.mySpecialMethod);
})();
</script>
I'm not sure if this would solve your issue or not, but its one way to handle it.

Calling As function from js problem

I have a swf file that is not controlled by me. The swf expects a javascript call to set some variables after initialization.
The swf is embedded using the swfobject and I'm trying to call the as function right after the embed. This appears to be too soon because I get an error. Everything else should be fine since calling the as function manually via firebug does not produce the error.
So the question is how do I call the function when the embed is complete?
Are you doing this while the page is still loading? Or from am onload handler?
If it's inline javascript I would suggest doing it in the onload handler from javascript which you can do like this -
window.onload = function() {
// your code here
}
it will run your code once the page is fully loaded.
This doesn't guarentee that the flash is initialised though. You could do that by having the flash make a callback to javascript once it is ready, but you said that the swf is not in your control. All I can really think of us using the onload method to make sure the page is finished loading, and then insert a short delay before trying to use it. Look at the setTimeout javascript function for that. Not a great solution though.
I found some code for checking whether the function exists yet. In summary:
if (typeof yourFunctionName == 'function') {
yourFunctionName();
}
Does that work for you? If it does then you can just wrap in a while loop. A bit less nasty than a setTimeOut!
When integrating Flash and HTML / JavaScript, there are several common approaches, which have been designed to eliminate this problem.
Pass in the variables as flashvars. They will be available to the flash movie immediately.
When the flash has loaded, it should call out to your page, normally there is a contract that defines the methods you can / must implement for the flash movie to call. For example, it would state that it will call MovieLoaded() when the flash file has loaded, and you could then put any scripts dependent on the movie being loaded within this method...
function MovieLoaded() {
doSomething();
}

Categories

Resources