Charles Yeung Charles Yeung - 16 days ago 7
jQuery Question

How to add or remove a js file in head

Suppose I have 3 language:

en
,
tc
,
sc
, I want to achieve the below condition

1) When the current is
en
, add
en.js
to head and remove js file
tc.js
and
sc.js
in
head


2) When the current is
tc
, add
tc.js
to head and remove js file
sc.js
and
en.js
in
head


3) When the current is
sc
, add
sc.js
to head and remove js file
tc.js
and
en.js
in
head


Can someone advise how to do that in jQuery?

Thanks

Answer

Here's a quick function that would load a script dynamically based on a language parameter.

addLanguageScript = function(lang) {
    var head = document.getElementsByTagName("head")[0],
        script = document.createElement('script');

    script.type = 'text/javascript'
    script.src = lang + '.js'
    head.appendChild(script);
};

addLanguageScript('en');

To remove the files you can do something like in jQuery, but keep in mind if the scripts where loaded they probably would have already had some effect.

$("script[src='en.js']").remove()
Comments