Hard worker
Hard worker

Reputation: 4046

How do I include a script within $(document).ready

I have approx 8k lines of code within a $(document).ready for a web app I am developing and I am now trying to partition the code up so it's easier to maintain.

I have tried including script tags without success

        <script type='text/javascript' src='./js/test.js'>{{html "</sc"+"ript>"}}

Can anyone advise either how to include script tags within document ready or how to partition up the javascript.

Thanks.

Upvotes: 2

Views: 1182

Answers (3)

Hard worker
Hard worker

Reputation: 4046

Found the answer - $.getScript('./js/test.js')

Upvotes: 2

Fernando Juarez
Fernando Juarez

Reputation: 87

Try this:

var html_doc = document.getElementsByTagName('head')[0];
js = document.createElement('script');
js.setAttribute('type', 'text/javascript');
js.setAttribute('src', '../js/test.js');
html_doc.appendChild(js);

//for IE
js.onreadystatechange = function () {
if (js.readyState == 'loaded' || js.readyState == 'complete') {
    DO SOMETHING
}
}
//for ff and chrome
js.onload = function () { DO SOMETHING }

with this code you can also do something when script is loaded

Upvotes: 1

kwikness
kwikness

Reputation: 1445

Not sure I completely understand your question, but you could put all the code (and then break up that code into separate functions) into a function and call just that one function from your document.ready.

The separate functions can be defined in a separate .js file if you'd like. Just make sure it's included in the html page like:

<script type='text/javascript' src='./js/test.js' />

Upvotes: 0

Related Questions