May 12, 2012
Jquery Is this the correct way?
Question by JCN
<script type="text/javascript">
if (SOMECONDITION) {
$("#scriptD").attr("src", "../../Scripts/A.js");
} else {
$("#scriptD").attr("src", "../../Scripts/B.js");
}
</script>
<script id="scriptD" src="" type="text/javascript"></script>
I am trying to insert a .js
file dynamically ( on the condition basis). But this is not working . Can anybody tell me whats the problem here?
Answer by Starx
One way to do what you are trying is using $.getScript()
if (SOMECONDITION) {
$.getScript("a.js");
} else {
$.getScritp("b.js");
}
And besides, you way will work, if you place the script after the <script>
element
<script id="scriptD" src="" type="text/javascript"></script>
<script type="text/javascript">
if (SOMECONDITION) {
$("#scriptD").attr("src", "../../Scripts/A.js");
} else {
$("#scriptD").attr("src", "../../Scripts/B.js");
}
</script>
This is because the script will not be able to find scriptD
on the DOM, when it is called before an element.