in Angular How to Dynamically Load javascript file depending of user language - javascript

I am using Angular for German, English, Spanish, French and Italian users
How to load the local file dynamically depend of User ' Language settings ? as an example :
For German users should Angular load:
https://code.angularjs.org/1.4.3/i18n/angular-locale_de-de.js
For Italian Users should Angular load
https://code.angularjs.org/1.4.3/i18n/angular-locale_it-it.js
I am thinking to use $local.id to define the user language then based on that I load the local file , but I don't know how or if there is any other solution to load the JS file dynamically also is appreciated .
regards

If you have a way to find the language before you load the angular version, you can use a map to find the correct url and just append a new script tag to the end of the body. Adding a script tag will automatically fetch this script and run it.
var language = 'someLanguage',
url = {
'someLanguage' : 'languageURL',
'otherLanguage' : 'otherlanguageURL'
}[language],
script = document.createElement('script');
script.setAttribute('src', url);
document.body.appendChild(script);
Maybe Angular has an angular-specific solution for internationalization, but alas I can't help you with that.

You just need to load the file using $http. In order to check the users locale you can look into angular-translate call preferredLanguage. It finds out from the user browser. Worth to take a look.

you can the angular.translate module for it..
https://angular-translate.github.io/

Related

How to read javascript file in frontend javascript/browser

Please read carefully before marking as dupe.
I want to read a javascript file on frontend. The javascript file is obviously being used as a script on the webpage. I want to read that javascript file as text, and verify if correct version of it is being loaded in the browser. From different chunks of text in the js file, I can identify what version is actually being used in the end user's browser. The js file is main.js which is generated by angular build.
I know we can do something like creating a global variable for version or some mature version management. But currently, on production site, that will mean a new release, which is couple of months from now. Only option I have right now is html/js page, which can be directly served from production site, without waiting for new release.
So my question is, is it possible we can read a javascript file as text in hmtl/js code in the browser.
an idea can be :
use fetch api to get a container that can be use to async load the script
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
use text() method which return a promise to get text content
fetch('http://localhost:8100/scripts.js').then((res) => res.text()).then(scriptContent => {
// scriptContent contain the content of your script
// if (scriptContent.includes('version : 1.1.1')
console.log(scriptContent);
});
this is absolutely not an efficient way, but since you want to work without any new version release or working with a version management system
here is the thing
assume file's checksum (md5 sha125 or anything) of V1.0 equals X and you will calculate before the coding part.
if checksum(X) != X{
location.reload()
}
would help for a security features too since it's an important project.
another way of controlling this situation is changing the main.js file's name if it is possible.

Changing Javascript source URL based on interface translation

I've run into a particularly troubling issue when trying to attach external libraries which URL changes based on the translation of the site.
To sketch the situation:
There's an element on a website I'm working on which loads in an external Javascript file to display certain contents.
This element is only shown on a specific page rendered by a module.
The languages are noted by subdomain, for example: uk.example.com, de.example.com
The script should be loaded based on this subdomain, so: uk.example.com/script.js, de.example.com/script.js , The path will always be the same.
The problem I'm running into:
While attaching the Javascript using a HOOK_library_info_alter() the Javascript source URL gets cached, this means that the uk version of the script gets loaded in on de de version of the site. It's not possible to change this system, these scripts need to be loaded using different URLs for reasons I wont go in.
I've tried adding the script using a HOOK_page_attachments to put the script in the header with the correct subdomain, except it is impossible to determine if the script only gets loaded on that specific page, with that specific element (Using library_info_alter I'm able to check if the $extension is correct)
Is there any possible solution to this problem?
I'm sorry if it's worded problematic, my english isn't exactly amazing.
Here is the outline of a possible solution:
function yourmodule_page_attachments(array &$page) {
$current_path = \Drupal::service('path.current')->getPath();
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
if($current_path == '/node/123') {
if($language == 'en') {
$page['#attached']['library'][] = 'yourmodule/extlib-en';
}
}
}
You will need to change "yourmodule", "/node/123" and "en" to fit, obviously, and define "extlib-en" and other language-specific libraries in yourmodule.liraries.yml, as defined in Drupal 8 documentation.

JavaScript and CSS dynamic versioning

I had a question regarding dynamic versioning of JavaScript and CSS file references in HTML files. For example:
script src = "test.js?v=1234"
And similarly with CSS references. I have done this in the past using ASP.NET, where I can call a function from the server side to generate a random number everytime the page loads ex:
"test.js?v=<%= myrandomfunc() %>"
I basically don't want the browser to get a cached copy of the css or js reference. I wanted to know if I can do this in JavaScript or jquery without using a server side language like asp or php etc.
Any help is much appreciated.
Thanks !
This is called file revving and it depends on what build system you're using. For Grunt, there's grunt-filerev, for Gulp, there's gulp-rev and gulp-filerev-replace.
If you don't yet use a build system, you might also want to check out Yeoman which will generate just about everything you need, including file revving.
I wanted to know if I can do this in JavaScript or jquery without
using a server side language like asp or php etc.
Yes.
var script = document.createElement('script');
script.onload = function() {
//do your stuff here
};
script.src = "http://whatever.com/the/script.js?v="+(+new Date());
document.getElementsByTagName('head')[0].appendChild(script);
Another option is to send the right headers :

How do I stop js files being cached in IE?

I've created a page that uses the CKEditor javascript rich edit control.
It's a pretty neat control, especially seeing as it's free, but I'm having serious issues with the way it allows you to add templates.
To add a template you need to modify the templates js file in the CKEditor templates folder. The documentation page describing it is here.
This works fine until I want to update a template or add a new one (or anything else that requires me to modify the js file).
Internet Explorer caches the js file and doesn't pick up the update. Emptying the cache allows the update to be picked up, but this isn't an acceptable solution. Whenever I update a template I do not want to tell all of the users across the organisation to empty their IE cache. There must be a better way!
Is there a way to stop IE caching the js file? Or is there another solution to this problem?
Update
Ok, I found this section in the CKEditor API that will allow me to use the "insert timestamp into the url" solution suggested by several people.
So the script now looks like this:
config.templates_files =
[
'/editor_templates/site_default.js?time=' + utcTimeMilliseconds
];
Thanks for your help guys.
You can add rand seed to your js file. I mean <script src='jsFile.js?seed=12345'
And every time you want to empty cache - change seed number
Update:
as I understood you have to write like this config.templates_files = [ '/mytemplates.js?seed=12345' ];
Youo can add a timestamp query parameter when you include your .js file..
so instead of <script type="text/javascript" src="somefile.js"></script> you can <script type="text/javascript" src="somefile.js?timestampgoeshere"></script>
this should make the file to always get reloaded (the timestamp needs to be dynamic and changing for each load of the page..)
I am afraid you'll have to hack into the FCKEditor code and force the client JavaScript to load fresh copy of the XML file. You can do so by appending a ?random=<a random number> to the URL of the XML file being requested. FCKEditor is opensource so you should be able to locate the lines the request the XML and modify accordingly.
Set Expires-Header accordingly, e.g. in Apache
ExpiresActive On
ExpiresByType text/javascript access
This is not recommended for a real web application, only for intranet scenarios because the files will not be cachable.
every time you load the js file, pass a variable of a random number as a variable.
src='/libs/js/myfile.js?4859487594573
same trick for ajax loaded files.
Multiple methods (don't need to do them all):
press ^F5 (control + F5) - that'll load without cache
set pragma/cache headers on sending
use a random variable in the GET query string
.NET / C# :
public static void DisallowBrowserCache( )
{
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false);
}
You could make ASP.NET write a js file to the outputstream (http://server.com/jsFile.aspx, set http headers), and control the caching behavior of the response with the above method.

Possible to use Jquery in a Js widget to be inserted on other sites

If I want to provide a widget on my website that other people can insert on their webpages, via :
Can I import and use Jquery in that file so that the user doesn't need to add it manually to his page.
How would I do this? (I'm new to Javascript too)
Thanks
You could do a simple copy and paste (i.e. copy the code in the jQuery file into your own JavaScript file).
If you wanted to keep the files separate, however, you could add the jQuery script to the DOM as follows:
var script = document.createElement("script");
script.src = "path/to/jQuery.js";
document.getElementsByTagName("head")[0].appendChild(script);
Steve
Here's a great post on that topic: http://alexmarandon.com/articles/web_widget_jquery/

Categories