简体   繁体   中英

Any JavaScript or jQuery Method to Load JS files synchronously?

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM