Nidheesh
Nidheesh

Reputation: 4562

Call a javascript src url dynamically

I was trying to include

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">

I need to edit the src path dynamically. That is, I need to change the protocol(http/https) dynamically. How can I write the src which calls the url like, location.protocol+ajax.googleapis......

Upvotes: 0

Views: 794

Answers (2)

RichieHindle
RichieHindle

Reputation: 281485

There's no need to do this dynamically - you can just say:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">

Starting the src with the double-slash means "use whatever protocol the page is using."

Upvotes: 3

Evan Trimboli
Evan Trimboli

Reputation: 30082

You can embed a script dynamically:

var src = 'myurl';
if (something) {
    src = 'other';
}
var script = document.createElement('script');
script.src = src;
document.getElementsByTagName('head')[0].appendChild(script);

Upvotes: 1

Related Questions