0

So essentially on page load I want to do the following:

<script>
    $(document).ready(function () {
        if (document.location.hostname == "somemachine.poc") {
            var fileref = document.createElement('script')
            fileref.setAttribute("type", "text/javascript")
            fileref.setAttribute("src", "myscript.js")
        }
    });
</script>

In theory and practice is this correct? for some reason I put it on my page and it doesn't work as expected, and doesn't even show up in the source of the page.

So what I will end up doing is checking for several domains, dependent on which domain a different src for the .js will load.

UPDATE

The answers below helped me fix the issue, I have a new issue which follows on naturally from this question which can be found here: Losing entire page DOM running javascript

4
  • The ready function doesn't run until the dom is completely ready. It won't be in the page source because it is loaded after the fact. If you use a tool like firebug to inspect your code you would see the changes if there are no errors. Commented Jun 7, 2012 at 13:00
  • is there anyway of running it earlier? Commented Jun 7, 2012 at 13:01
  • 1
    I think you can use $.getScript here. Even so, can't you get the server to send a script based on the domain? Commented Jun 7, 2012 at 13:01
  • try to append the this "fileref" to header tag . Commented Jun 7, 2012 at 13:03

3 Answers 3

1

You have to add the script to the document.

document.body.appendChild(fileref);

It still won't show up in the source though. The DOM, as modified by JS, is not the source. You would have to use a DOM viewer to see it (e.g. Chrome Developer Tools or Opera Dragonfly).

Sign up to request clarification or add additional context in comments.

Comments

1

you should also inject your script element in the document, e.g.

document.body.appendChild(fileref);

creating element only is not enough to make it run as far as it's not appended as part of the DOM

Comments

1

Not sure what you're trying to do but you never actually add the <script> element to the DOM in the code you provided. You would need to do something like:

document.getElementByTagName("head")[0].appendChild(fileRef);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.