Reputation: 5831
I have a js.js script which handles all my jQuery functions. I call them one by one after document ready, like so:
function 1(){}
function 2(){}
jQuery(document).ready(function($){
function 1();
function 2();
});
I also have an external javascript which I call inside the tags of my website:
<script type="text/javascript" src="myscript"></script>
The problem with this script is that it loads from an external website and sometimes is very slow, slowing my whole website.
Can I load it inside my js.js file, after document ready? lets say before function 2()?
Any ideas?
Upvotes: 0
Views: 4387
Reputation: 29739
Alternatively to SLaks` answer, you can use a library for organizing your JavaScript file includes. It gets useful if you have many files and dependencies.
Have a look at head.js, for example.
head
.js("jquery.js", "selectivizr.js") // these are loaded in parallel
.js("jquery-ui.js"); // this is loaded after the scripts above
head.ready(function() {
jQuery(document).ready(function($) {
function1();
head.js("other-script.js", function() {
function2();
// your code
});
});
});
function 1(){}
function 2(){}
A better solution would be to organize all your javascript functionality into seperate files and just use headjs loading:
head
.js("jquery.js", "selectivizr.js") // these are loaded in parallel
.js("jquery-ui.js"); // this is loaded after the scripts above
.js("app1.js"); // contains function1()
.js("app2.js"); // contains function2()
head.ready(function() {
jQuery(document).ready(function($) {
// your code
});
});
Upvotes: 1
Reputation: 1307
first, be sure to put your <script type="text/javascript" src="myscript"></script>
at the end of your html page, just before the </body>
end tag.
Also, you can use RequireJS, that is a script allowing you to load aynchronously your js file when you need them, even after the entire page is loaded. You can do it by yourself by loading your script via Ajax and manage the workflow manually, but I suggest you to use this powerful script instead.
Upvotes: 0