Any JavaScript or jQuery Method to Load JS files synchronously? - javascript

I'm loading user control through jQuery in my asp.net page.
User control contains JavaScript files, while loading the user control all my js load at one time which are dependent on each other and they tend to give error while all file load at one time. So I want that my JavaScript file to load synchronously one by one , as one file get completely loaded than next file should start loading .
Is there any way to set synchronously mode in JavaScript? or any JavaScript to set this? Any pointer or suggestion would be really helpful.

You should use jQuery.load() to load only a HTML fragment and not a full page with the scripts. jQuery use DOM structure of the loaded document to modify the DOM structure of the corresponding part of your page (controls).
In general you can use jQuery.ajax to load a script, but I recommend you to use the simplified form jQuery.getScript() instead. jQuery.getScript() can be used to load a JavaScript file from the server using a GET HTTP request and then execute it. Using success event handler you can do some action after the script are loaded.

JS files are loaded in the order you put them in your HTML code.
For example,
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"></script>
You always need to load jQuery before jQuery UI (or UI will not be recognize since it uses the jQuery $ shortcut) so you must put the line with jQuery before the one with jQuery UI into your HTML.
And when your page is fully loaded, js will start thanks to window.onload, $(document).ready(function(){}); for jQuery or via the first command it will encounter.

JavaScript files always load synchronously. In fact, JavaScript always runs synchronously because it is single threaded.
My guess is that you need to work out which order to include the files so that it runs properly. You can use the window.onload event to run script once all of the JavaScript and images have been loaded.

Related

HTML content loaded via AJAX loads external JavaScript out of order

Here's the scenario, not sure what I'm missing.
Page A.htm makes an ajax request for page B.htm, and inserts the response into the page.
Page B.htm contains links to several other JS files, many of which contain a document.ready() function to initialize them.
This works fine when A.htm and B.htm are on the same server but not when they are on different servers.
What I think I'm seeing here, is that when page A and B are on different servers (cross domain ajax), the external resources are being returned asynchronously, or at least out of order, so scripts are executing expecting JQuery.UI to be loaded already, when it is not.
Appreciate any pointers or advice. Apologies for the poor explanation.
You are injecting HTML + script tags via jQuery. In this case *:
HTML content except scripts are injected in the document
Then all scripts are executed one by one
If a script is external then it is downloaded and executed asynchronously
Therefore an external or inline script that depends on jQuery UI might execute before jQuery UI.
One possible solution is to change the way your pages work:
Get rid of external scripts in pageb.html but keep inline scripts
Load the required scripts in pagea.html
Load pageb.html
Another solution is to roll your own jQuery function that will:
Strip all <script src> elements from HTML
Download and execute those scripts in order
Inject the remaining HTML
* The exact behavior is not documented. I had to look into the source code to infer the details.
you are correct in your impression that the issue is a difference in how the requests are handled cross-domain.
Here is a link to get you on the right track : How to make synchronous JSONP crossdomain call
However, you will have to actually re-achitect your solution somewhat to check if the resource has been loaded before moving on. There are many solutions (see the link)
You can set a timer interval and check for something in the dom, or another reasonable solution (despite it's lack of efficiency) is to create a "proxy" serverside (eg php) file on your server and have that file do the cross-domain request, then spit out the result.
Note that since jquery UI is a rather large file, it's conceivable that the cross-domain request finishes first, and executes immediately, even though jqueryUI is not loaded yet. In any case, you're going to have to start thinking about having your app react rather than follow a sequence.

Are JavaScript files downloaded with the HTML-body

I have a Java Web Application, and I'm wondering if the javascript files are downloaded with the HTML-body, or if the html body is loaded first, then the browser request all the JavaScript files.
The reason for this question is that I want to know if importing files with jQuery.getScript() would result in poorer performance. I want to import all files using that JQuery function to avoid duplication of JavaScript-imports.
The body of the html document is retrieved first. After it's been downloaded, the browser checks what resources need to be retrieved and gets those.
You can actually see this happen if you open Chrome Dev Console, go to network tab (make sure caching is disabled and logs preserved) and just refresh a page.
That first green bar is the page loading and the second chunk are the scripts, a stylesheet, and some image resources
The HTML document is downloaded first, and only when the browser has finished downloading the HTML document can it find out which scripts to fetch
That said, heavy scripts that don't influence the appearance of the HTML body directly should be loaded at the end of the body and not in the head, so that they do not block the rendering unless necessary
I'm wondering if the javascript are downloaded with the html body during a request
If it's part of that body then yes. If it's in a separate resource then no.
For example, suppose your HTML file has this:
<script type="text/javascript">
$(function () {
// some code here
});
</script>
That code, being part of the HTML file, is included in the HTML resource. The web server doesn't differentiate between what kind of code is in the file, it just serves the response regardless of what's there.
On the other hand, if you have this:
<script type="text/javascript" src="someFile.js"></script>
In that case the code isn't in the same file. The HTML is just referencing a separate resource (someFile.js) which contains the code. In that case the browser would make a separate request for that resource. Resulting in two requests total.
The HTML document is downloaded first, or at least it starts to download first. While it is parsed, any script includes that the browser finds are downloaded. That means that some scripts may finish loading before the document is completely loaded.
While the document is being downloaded, the browser parses it and displays as much as it can. When the parsing comes to a script include, the parsing stops and the browser will suspend it until the script has been loaded and executed, then the parsing continues. That means that
If you put a call to getScript instead of a script include, the behaviour will change. The method makes an asynchronous request, so the browser will continue parsing the rest of the page while the script loads.
This has some important effects:
The parsing of the page will be completed earlier.
Scripts will no longer run in a specific order, they run in the order that the loading completes.
If one script is depending on another, you have to check yourself that the first script has actually loaded before using it in the other script.
You can use a combination of script includes and getScript calls to get the best effect. You can use regular scripts includes for scripts that other scripts depend on, and getScript for scripts that are not affected by the effects of that method.

GWT : Fire and event after javascript and css loads

I am working on a GWT project and making a JSNI call to a javascript function on some event.
Issue is after my event fires (on tab load), the jsni call to js function is getting called even before the javascript and css have been loaded and so it gives error that function not exists.
What is the best way to handle such a scenario ?
The best way is to insert the external script in the header of your index.html file (or whatever file serves your gwt nocache file).
<header>
<script type="text/javascript" src="my-erternal-js.js"></script>
</header>
This way you can be share that the JavaScript file is loaded before GWT tries to call it from JSNI.
Sounds like what you want is to inject the script and run your code in a callback that's fired only when the script is finished loading. ScriptInjector does just that.

javascript stream wrapper, intercept JS file contents

In PHP there's a function called stream_wrapper_register. With that i can get the file contents of every PHP file that is about to be included. So that basically gives me control over the 'code' that will get parsed.
I was wondering if there's something like this in javascript too? So suppose i include my file:
<script type="text/javascript" src="js/myfile.js"></script>
My code in that file then sets up the stream wrapper (suppose this is available in JS too). Now i want to be able to get the file contents of every other javascript file that will be included:
<script type="text/javascript" src="js/somefile.js"></script>
<script type="text/javascript" src="js/someotherfile.js"></script>
But this ofcourse must happen before before the browser actually executes those files.
So is there a way to intercept that somehow?
$.ajax("/path/to/javascript.js").done(function(source) {
eval(transmogrifySourceCode(source));
});
I used the jQuery syntax because AJAX-style gets are much easier that way, and you'll have to provide your own transmogrifySourceCode function to edit the source before you load it.
I do wonder why you'd want to do, that, though. You should be in full control over your input source, so why not just excise the code you don't want on the server?
No, you can't. Alone for security reasons you won't be allowed to get every script's content.
For Opera, there is a special BeforeScript event which can be listened to from local user scripts.
So there is no (good) way to detect (dynamically added) <script> elements in a page and prevent them from loading and executing a script. Yet you could load the script files by ajax, respecting the same-origin-policy (!), and evaling their modified contents as #DavidEllis suggested.
Elsewise, you need to proxy all script inclusions over your server and modify them there.

Can I load JavaScript code after the rest of page loads?

I have a section of a webpage that loads a JavaScript file from an external source and then kicks off an Ajax query.
When I load the page, I see the browser saying "waiting for example.com" a lot, so I think the dependency on this external JavaScript is slowing my initial page load.
Is there a way I can load this external JavaScript asynchronously so it doesn't slow the loading of the rest of my page at all?
It's good practice to put JS at the bottom, right above the closing body tag. In addition, use load events window.onload or $(document).ready() to fire your JavaScript after the page has loaded.
As far as loading JavaScript files themself asynchronously or on demand, you could inject it from another JavaScript function or event. But really you are doing the same thing as placing it at the bottom.
Check out the YSlow Guidelines for front-end optimizations.
You could use jQuery's .getScript() method, which is simply a wrapper for an AJAX call.
http://api.jquery.com/jquery.getscript/
This makes the request asynchronous, and gives you a callback that runs after the script has loaded.
You can see my answer here: Dynamic (2 levels) Javascript/CSS Loading
And grab the script from here (see the source). Use it at the bottom, and your scripts will not block other resources (and if you got more than one they will be downloaded in parallel cross-browser).
I wrote a library to asynchronously load javascript files with callbacks for when it loads:
https://github.com/ssoroka/sigma
Sigma.async_script_load('http://example.com/underscore/underscore-min.js', '_', function() {
_([1,2,3,2,3,1]).uniq();
});

Categories

Resources