Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
169
rated 0 times [  175] [ 6]  / answers: 1 / hits: 123453  / 13 Years ago, mon, september 5, 2011, 12:00:00

In my page body, I need to insert this code as the result of an AJAX call:



    <p>Loading jQuery</p>
<script type='text/javascript' src='scripts/jquery/core/jquery-1.4.4.js'></script>
<p>Using jQuery</p>
<script type='text/javascript'>
$.ajax({
...
});
</script>


I can't use $.load() since the document has already loaded, so the event doesn't fire.



Is this safe? If not, how do I make sure the jquery script has loaded before my custom, generated code is executed.


More From » jquery

 Answers
25

It is pretty safe. Historically, <script> tags are full blocking, hence the second <script> tag can't get encountered befored the former has finished parsing/excuting. Only problem might be that modern browsers tend to load scripts asynchronously and deferred. So to make sure order is correct, use it like this:



<p>Loading jQuery</p>
<script type='text/javascript' async=false defer=false src='scripts/jquery/core/jquery-1.4.4.js'></script>
<p>Using jQuery</p>
<script type='text/javascript'>
$.ajax({
...
});
</script>


However, it's probably a better idea it use dynamic script tag insertion instead of pushing this as HTML string into the DOM. Would be the same story



var scr  = document.createElement('script'),
head = document.head || document.getElementsByTagName('head')[0];
scr.src = 'scripts/jquery/core/jquery-1.4.4.js';
scr.async = false; // optionally

head.insertBefore(scr, head.firstChild);

[#90260] Saturday, September 3, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
danalexc

Total Points: 114
Total Questions: 119
Total Answers: 103

Location: Hungary
Member since Wed, Nov 9, 2022
2 Years ago
;