I am implementing multilingual support into my webpage. I would like to minimize the page blinking caused from page reload, and I came to the idea to change page language without forcing the whole page to reload. To achieve this, the only possible way that comes to my mind is with the use of JavaScript:
I dynamically load appropriate language .js file with appropriate translations
I manually go through every text object on the page and update it by re-sending the appropriate new text value
To provide you with example code, I paste a code that will update just submit buttons. On the language change, I call a function that loads appropriate .js language file dynamically.
var fileRef = LoadJsCssFile("Language/svk.js", "js", UpdateLanguage);
After the language .js file is fully loaded, I call the function that updates every element containing text on the webpage:
function UpdateLanguage()
{
var buttons = document.getElementsByClassName("submit_button");
for (buttonID in buttons)
{
buttons[buttonID].innerHTML = lang.SUBMIT;
}
};
Manually updating every text object in the webpage is complex and error prone. As I am not very experienced with JavaScript yet, I was thinking, if there is a way to simply refresh the all key elements in the webpage with one JavaScript command without casing the webpage blink?
If you have any other idea, how to effectively implement language change without page blink, I am interested to know. :-)
I found a solution on my own:
I prepare several javascript language files containing strings per every keyword
On language selection button, I import appropriate language file for the language I wish to use
I manually update every text on the webpage through javascript.
The above solution is suitable for smaller sites. for large ones, that would be a lot of work, to update every single text string through javascript.
Related
I'm building a Chrome Extension.
The extension injects some CSS and JavaScript when .html files on the users local drive are loaded in the browser (file:///).
My extension adds an extensive UI to the page that allows the user to modify and manipulate the original source code from their .html file.
The primary purpose of the extension is debugging and QAing HTML email newsletters. Here's just a few things that it does:
Checking links for the appropriate parameters.
Toggling images off and on to simulate popular email clients.
Displaying the source code side-by-side to show a desktop view and multiple mobile sized views.
A function that takes the original HTML and generates a plain text version.
A function that toggles <style> blocks off and on to simulate popular email clients ignoring them.
Email files are backed up via Dropbox and the Dropbox API is integrated to allow for quick sharing right from the email newsletter.
Until now I've been using javascript in my injected content script like this to create all of my menu items.
var debugOrb = document.createElement("div");
debugOrb.id = "borders-orb";
debugOrb.className = "borders-orb orb glyph";
debugOrb.addEventListener("click", toggleBorders, false);
orbsBottom.appendChild(debugOrb);
Here's an extended view of the code I've written to create all of these toggles/menu items: http://pastebin.com/LQTkNhpP
My problem is that now I'm going to be adding a LOT more clickable menu items like this. And it feels like if I do, it's going to get out of hand really quick. Especially since I'll be nesting a lot of divs to make the whole thing look organized and using JavaScript to create lots of text nodes too.
My first thought was what if I could just create my entire menu in regular HTML, then just inject that file into the page with the javascript in my content script. I'm barely intermediate level with JavaScript though. And as I understand it, if I did this, I'd lose my ability to use onclick handlers for all of these divs I'm creating.
Is there an efficient way to handle my goal that I'm not aware of?
Notes:
I'm not using any framework/plugins like React, Angular, or jQuery.
Once the html is added you can always get the element by id and then add an event listener to that element. You can have functions relate to the divs and then onload create the event listeners. element.addEventListener ('click', function);
I have a page with a lots of javascript. However, the page once rendered remains static, there are no moving things or special effects, etc... It should be possible to render the same HTML without any javascript at all using only the plain HTML and CSS. This is exactly what I want - I would like to get a no javascript version of the particular page. Surely, I do not expect any dynamic behavior, so I am OK if buttons are dead, for example. I just want them rendered.
Now, I do not want an image. It needs to be an HTML with CSS, may be embedded with the HTML, which is fine too.
How can I do it?
EDIT
I am sorry, but I must have not been clear. My web site works with javascript and will not work without it. I do not want to check if it works without, I know it will not and I really do not care about it. This is not what I am asking. I am asking about a specific page, which I want to grab as pure HTML + CSS. The fact that its dynamic nature is lost is of no importance.
EDIT2
There is a suggestion to gram the HTML from the DOM inspector. This is what I did the first thing - in Chrome development utils copied as HTML the root html element and saved it to a file. Of course, this does not work, because it continues to reference the CSS files on the web. I guess I should have mentioned that I want it to work from the file system.
Next was to save the page as complete with all the environment using some kind of the Save menu (browser dependent). It saves the page and all the related files forming a closure, which can be open from the file system. But the html has to be manually cleaned up of all the javascript - tedious and error prone.
EDIT3
I seem to keep forgetting things. Images should be preserved, of course.
I have to do a similar task on a semi-regular basis. As yet I haven't found an automated method, but here's my workflow:
Open the page in Google Chrome (I imagine FireFox also has the relevant tools);
"Save Page As" (complete page), rename the html page to something nicer, delete any .js scripts which got downloaded, move everything into a single folder;
On the original page, open the Elements tab (DOM inspector), find and delete any tags which I know cause problems (Facebook "like" buttons for example) (I also try to delete script tags at this stage because it's easier) and copy as HTML (right-click the <html> tag. Paste this into (replace) the downloaded HTML file (remember to keep the DOCTYPE which doesn't get copied;
Search all HTML files for any remaining script sections and delete (also delete any noscript content), and search for on (that's with a space at the start but StackOverflow won't render it) to remove handlers (onload, onclick, etc);
Search for images (src=, url(), find common patterns in image filenames and use regular expressions to replace them globally. So for example src="/images/myimage.png" => |/images/||. This needs to be applied to all HTML and CSS files. Also make sure the CSS files have the correct path (href). While doing this I usually replace all href (links) with #;
Finally open the converted page in a browser (actually I tend to do this early on so that I can see if any change I make causes it to break), use the Console tab to check for 404 errors (images that didn't get downloaded or had a different name) and the Network tab to check if anything is still being loaded from the online version;
For any files which didn't get downloaded I go back to the original page and use the Resources tab to find them and download manually;
(Optional) Cull any content which isn't needed (tracker images/iframes, unused CSS, etc).
It's a big job. I'd love a tool which automated all that, but so far I haven't found one. The pages I download are quite badly made (shops) which have a lot of unusual code, so that's why there are so many steps. You might not need to follow every step.
I am building a website using PHP and JavaScript, and I feel that I have a good grasp on where to include my JavaScript, but a more specific situation has come up that has me confused. I currently have all of my JavaScript in one external file, which is being included on every PHP page.
Let's say that I have a paragraph with an id='myParagraph' and I need to highlight this paragraph in red with JavaScript on page load. This paragraph is only on ONE PHP page and my website has about 50 different pages. I immediately assumed that I should throw some code into my one external JavaScript file, something like:
$('#myParagraph').css('color', 'red')
and the paragraph would be highlighted when that page loads.
My question is: is this the best way to do it? To my understanding, every time I load a page it will be searched for an element with the id myParagraph, yet 98% of my pages won't even have that id. Is this wasteful? Should I instead include the following code:
function highlightParagraph()
{
$('#myParagraph').css('color', 'red')
}
in my one JavaScript file and then put some inline JavaScript in the PHP file with the id myParagraph to call the function highlightParagraph() when it's loaded? That way, only the one page with myParagraph will be searched and highlighted.
I feel like option 2 is the best, but I read all the time not to use inline JavaScript.
edit: I realize that for this example you would just use CSS. I'm just using it to get my question across
You should have a one "big" js file with the infrastructure functions and all the pages should have a reference to it.
Then each page should reference another js file with the functions related only.
The good things about using external js files are:
The files are cached after the first download => Faster surfing.
Separate of concerns, you keep the presentation tier away from the scripting tier.
Another important note:
The best way to change css is with css... not javascript.
I
If you change the element style on DOM ready, just add the element definition
#myParagraph{color: red;}
The problem with inline JavaScript is you might be starting with a few lines now, but in a few weeks or months, it will add up and be a lot of inline JavaScript.
That is bad, because inline JavaScript can't be cached by the browser like JavaScript files that you include with <script src="path/to/file.js" />.
That's bad because you add a lot of content that will be fetched every single page view by the user, adding load on your server bandwidth and slowing page load for the user.
If it's just a few selectors, don't worry; The time wasted on it won't cause any browser to sweat.
Though, if it becomes a lot of code for a different page/module of your site, you might want to split it into a different JavaScript file and include just that file when certain pages are loaded.
That way, the browser will cache that file and save that bandwidth for you and the user.
I wouldn't be too surprised if many people disagree with me (violently even) but I don't have a problem with putting a javascript tag with specific javascript for that page in the header if it will reduce the number of files or overall complexity of the project. Most of the core things that are done everywhere should of course be separated in another file but if it is a one page deal, then I would go for cleanliness.
The same goes for css, if it is specific to that page just put a css tag in the header with the specific changes that differ from the master css file. BTW as everyone is pointing out, this is a case where you want to just use CSS.
I'm trying to build a single-page app that has several views (screens, page contents)
My App's UI has a permanent menu bar and a "view area" which retrieves a view via Ajax, based on menu selections. This works great for simple HTML content and keeps my menu-script running on the background despite which view is being displayed.
But what if my view needs an additional script? How do you load and execute a script as a result of a view change (=a page fragment was loaded as a result of a button click) also, how do I get rid of that script when I choose a different view?
I know I can embed a script-tag into the page fragment and write the code there, but I'm really looking for a more robust way of doing this, preferably so that an instance of an object is created when the view is loaded and then discarded when the view changes.
yepnope.js is a great conditional loader. You could use it to check certain conditions (e.g. view, state) before loading a script. I don't think it has the ability to remove a script that's already been loaded, though.
You can use javascript to add a <script> tag in the same way you would any other tag.
The hardest part is knowing where to place it, but if you have control over your markup, this isn't too big a barrier.
Something along these lines:
function DST(url)
{
var s = document.createElement(’script’);
s.type=’text/javascript’;
s.src= url;
document.getElementsByTagName(’head’)[0].appendChild(s);
}
If you need something to happen automatically when you load that script, you should be able to use a self executing anonymous function to do the job.
(function(){alert('this happened automatically');})();
If you need to pass anything in to the function it would look like this:
(function($){alert('this happened automatically');})(jQuery);
If you really need to discard the scripts, you can delete the nodes, but it might be better to leave them in, in case a user reactivates a view, so you don't have to make the AJAX call and associated HTTP request, allowing the page to load faster.
I was trying to write a global JavaScriptfunction which overrides any HTML object (img, iframe, links and so on) before it being loaded by the page. The purpose of the overiding action was to to change the SRC and HREF of these objects using the DOM to any other link.
Unfortunately I didn't find any solution to that without firstly loading the object and only then changing it by the onload event.
My second option was to change the SRC and HREF by matching these attributes with a regular expression and replacing the resultant values. I prefer not to do so because it's slow and consumes a lot of time.
I would be glad if someone can share with his/her experience and help me solve this out.
JavaScript only works within the DOM.
You could however, load the page via AJAX, get the content and do any string manipulation on it.
If you are trying to modify items that exist in the static HTML of the page, you cannot modify them with javascript until they are successfully loaded by the browser. There is no way to modify them before that. They may or may not be visible to the viewer before you have a chance to modify them.
To solve this issue, there are a couple of options.
Put CSS style rules in the page that causes all items that you want to modify to initially be hidden and then your javascript can modify them and then show them so they will not be seen before your modification.
Don't put the items that you want to modify in the static part of your HTML page. You can either create them programmatically with javascript and insert them into the page or you can load them via ajax, modify them after loading them via ajax and then insert them into the page.
For both of these scenarios, you will have to devise a fallback plan if javascript is not enabled.