execute code in script element after external js file loaded - javascript

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.

Related

Does a javascript function call run before the entire script is finished parsing?

I know Javascript executes code in sequential order. However I am always trying to identify whether any of the code run instantly, "line after line", after each function is compiled executed, or do all the immediate functions calls in that script wait for the entire script to finish parsing before anything is actually run.
I'd like a better understanding of the way javascript parses and execute code. Mainly for external scripts, which seem a bit hard to observe in a console log.
One applicable use, is to try and intercept the 'interactive' document.readyState as early as possible within an external script, due the fact that "interactive" state can fire extremely early at times. As per http://bugs.jquery.com/ticket/12282#comment:15
No. The entire content of a script tag (regardless of whether it is inline or external) must be parsed before it can be evaluated.
This is because of the way javascript 'hoists' variable and function declarations to the top of their scope: http://elegantcode.com/2011/03/24/basic-javascript-part-12-function-hoisting/
Javascript is *compiled and executed one script (tag) at a time. So within each script tag, be it inline or sourced from a file, the entire code is compiled and then executed. But each individual script tag is compiled and executed in sequence.
You can check this by simply running the following two examples:
Example 1:
<html>
<script>
alert(x);
var x;
</script>
</html>
The code above will alert "undefined". On the other hand..
Example 2:
<html>
<script>
alert(x);
</script>
<script>
var x;
</script>
</html>
The code above will trigger an error because x doesn't exist.
note: * JavaScript function declaration and evaluation order

How to onload two javascript files?

I have two different javascripts. I would like to start a function only after both of those js files or scripts have loaded, because they need to access each other's functions and/or variables.
I don't know which one will load first.
What is the proper way of doing it?
NOTE: one of the scripts (A) loads data asynchronously and the script (B) needs to wait till all the data is loaded and started before it can continue (ex youtube video is loaded from (A) and needs to start playing before (B) can execute)
<script> are loaded synchronously in general. The evaluation of the document stops an waits until the script is loaded and executed. It is handled that way, because the script might interfere with the document by using something like document.write(), so the parser can not be sure, that the rest of the document stays the way it appears at that moment.
So to execute you scripts after they have loaded, just place a 3rd <script> tag holding the start-code behind those two, that are loading the scripts.
<script src="scriptA.js"></script>
<script src="scriptB.js"></script>
<script>
// start something of scriptB
scriptB.start();
</script>
As scripts are loaded synchronously, just load the script that executes their functions after those two files.
Anyway, if you have scripts with dependencies, I would encourage you to use a module loader, such as RequireJS. That way, you could define which modules/files should be loaded before the execution begins.

Chrome extension inject script before page load

I am developing a Chrome application on a 3rd party website.
The document that I am trying to alter has the following page format:
<head>
.
.meta data here
.
</head>
<body>
<script type="text/javascript">
function a1(){
..contents of function a1
}
</script>
.
.other contents of body
.
<script type="text/javascript">
a1(); // <-- I don't want this to be executed
</script>
</body>
My problem is I want the entire page to be loaded, except the function call a1();
So I thought of a simple solution: BEFORE the function definition ie; function a1(){..}, I want to create a1 as a CONSTANT function which does nothing, therefore rendering the a1() call useless.
Problem is that if I define the function to be constant in my js which run_at document_start, the execution environment is different, hence it wont affect the page.
So the alternate to run in the same execution environment is by INJECT the code using innerHTML+=" ... "
Another alternate is to construct a script element using "createElement" and the src is an external js file which has to be loaded before execution.
Both the alternatives does not work, as the parse tree isn't created in the run_at document_start script.
So, I thought of an other solution. I added the listeners for DOMModifySubTree event, hoping to alter the parse sequence(I know, it sounds funny :)) so that the function isn't called. Doesn't help.
So, my question is how do I prevent the call to a1() function??
P.S - I cannot contact the 3rd party website developer.
Greasemonkey is what you're looking for.
It's a Firefox extension that injects your own scripts in webpages of your choice.
Visit wiki.greasespot.net to get started on writing scripts.
Fontunately, Chrome natively supports Greasemonkey scripts. See this page for more info.
Sorry for the late late reply. What I had originally done to skip the function call is that I ran a script at document start and injected it into the "document" (as JS runs in separate envi). In that injected script I used
const a1=function(){};
This way, when the function is being declared again, it is NOT overwritten, hence the function is not executed (ie; it is executing our dummy function), thus essentially breaking the code. :)

putting jquery and javascript into external file

A lot of my pages have amll bits of jquery.
Im thinking of putting them into one external file with one $(document).ready(function() {
and everything in there.
is this a good/bad idea?
will each page be slower overall if there is more code to execute even if its not relevant to the page? i imagine each line of code in the external script gets executed when the dom is ready..? or is my understanding wrong?
will each page be slower overall if there is more code to execute even if its not relvamnt to the page?
The external script file may have some overheads for loading, but if you use the script on any number of pages more than one, external is a good idea; it'll be cached and be instant.
i imagine each line of code in the external script gets executed when the dom is ready..? or is my understanding wrong?
Yes. If you wrap your code in a function as an argument to $(document).ready() it gets executed on DOMContentLoaded.
If you put all your bits of JS into one page - without calling them as functions- then, yes, they will get executed everytime you include them. It would be better to put the common functions into an external scripts and keep it there. This will increase your code reuse as well as speed up page load because your JS will be cached.

Running Javascript from external file loaded with AJAX

I've been trying to get this sorted all day, but really cant figure it out. I've got a page with <div id="ajax"></div> that is populated off a tab based menu pulling in a snippet of HTML code stored in an external file that contains some javascript (mainly form validation).
I've seen in places that I need to eval() the code, but then on the same side of things people say its the last thing to do.
Can someone point me in the right direction, and provide an example if possible as I am very new to jQuery / JavaScript.
Many thanks :)
pulling in a snippet of HTML code stored in an external file that contains some javascript (mainly form validation).
Avoid doing this. Writing <script> to innerHTML doesn't cause the script to get executed... though moving the element afterwards can cause it to get executed, at different times in different browsers.
So it's inconsistent in practice, and it doesn't really make any sense to include script anyway:
when you load the same snippet twice, you'd be running the same script twice, which might redefine some of the functions or variables bound to the page, which can leave you in extremely strange and hard-to-debug situations
non-async/defer scripts are expecting to run at parse time, and may include techniques which can't work when inserted into an existing document (in the case of document.write this typically destroys the whole page, a common symptom when trying to load third-party ad/tracking scripts).
Yes, jQuery tries to make some of this more consistent between browsers by extracting script elements and executing them. But no, it doesn't manage to fix all cases (and in principle can't). So don't ask it to. Keep your scripts static, and run any binding script code that needs to happen in the load callback.
If you fetch html via Ajax, and that html has a <script> tag in it, and you write that html into your document via something like $('#foo').append(html), then the JS should run immediately without any hassle whatsoever.
jquery automatically processes scripts received in an ajax request when adding the content to your page. If you are having a particular problem then post some code.
See this link
dataType: "html" - Returns HTML as
plain text; included script tags are
evaluated when inserted in the DOM.

Categories

Resources