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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!