How can I: Replace all instances of an old 'base' href on archived website with a new one for quick changeover? - javascript

This problem has come up before for me. I had to manually (or using search/replace in an HTML editor) replace all instances of EXAMPLE.COM with MYTESTSERVER.COM/EXAMPLE for sake of links/images not being broken (This includes any values for HREF or SRC properties--especially these types, actually).
The site was made in 2012... it does include template files (WordPress theme I developed painstakingly over the course of 5-6 months). The template files aren't really what I'm concerned with... it's the countless references to the old domain that was used within the "post" files...
This was an "Online Literary Journal", so there's enough supporting graphics spread throughout the individual posts' code to make me want to find a script to stick in the header.php or footer.php which will change this all over for me on each browser load, without me having to alter the code much (at least for the time being while this is still an "archived" client site)...
THANKS!
NOTE: I am NOT actually using any kind of <BASE> coding... as in building links through the structure of the site's code based on a single instance of a base href. This site was one of my first WordPress projects, and furthermore one of my first "dynamic-like" sites... so I also did not utilize WordPress' php function of bloginfo()... WISH I HAD NOW LOOKING BACK!
**also now i realize that using PHP code within posts isn't the easiest thing to do... nor was it then, so the links were coded as static.

Download the site to your local machine
Use Sublime Text:
Press cmd + shift + F / ctrl + shift + F (Win)
Select the ... symbol & Choose add folder
Choose your folder and do your 'global' search and replace.
Note: Might be a good time to entertain using partials and setting up light static site generator to make this work easier going forward

Related

How to link to a file one level above the current one

In CSS I know that I can reference/link to another file using either of the following:
photo.jpg or ./photo.jpg for a file in the same location as the one I am working in, and photo-folder/images/photo.jpg or ./photo-folder/images/photo.jpg to link a file in one or more directories below/inside the parent directory of the one I am working in.
I also know the same idea applies in HTML like ./[href] or [href].
But I am wondering, let's say the positions of the files in my example are reversed, that is, I want to link to a photo in a directory which is the direct/indirect parent of the file I'm working in. How would I call that file without using the full drive address such as C:/Users/Username/Code/etc/photo.jpg, while my working file is C:/Users/Username/Code/etc/code/file.css...
How is it done in these languages: HTML, CSS, JS, Python? (You are welcome to answer for other languages, I might need it later! :D)
Side question: is there any technical difference between ./file and file, and would it be preferable to stick to one format over the other (e.g. to prevent problems, for readability, etc)? Though I have never run into any problems using either, or even combining both in the same project...
To get to parent directory use ../, this is "per directory", so if you need access several levels up, you'd need use: ../../../ (for 3 levels)
As of using ./ for current directory - it's redundant
As far as I know this is pretty much applies to all languages, however in HTML/CSS there is another relative path that can be used to get to the root of the domain: / (no dots)
so for example if you open https://example/some/long/path/file.html and need access to file at http://example/file.jpg you simply put as relative path: /file.jpg

Load Random Image From Directory on Page Load Without a Listed Array of File Names

I've done some looking around on the site and every time I pull up a solution to this problem, one of the requirements is to have a naming convention and a list of every image to pull from the directory (example: image1.jpg, image2.jpg, etc.) All of the file names are different and there are thousands of them to pick from (so listing each one as a random opportunity in an array is not going to work).
I typically use CMS services and I'm writing this webpage from scratch in Notepad in an attempt to better my coding skills... and I'm not sure where to begin. I'm decent with HTML and CSS, but j Query and JavaScript are not my friends haha.
Thank you for any help! (Even if it's just pointing me to a tutorial or a solution I could not find!!!)
Are all file names image1 image2 image3 etc? Then you could try to generate a random number, create a new img element and have it's source pointing to image+randomnumber.jpg and append it to the DOM
One of the main problems your facing here is about your thinking when it comes to how content is delivered, in a standalone static website you do not have access to the file system. This means that if we want to query things outside of the browsers context we are not allowed, obviously without being able to access directories we can not generate a list of file names which can be loaded.
If your wondering why we can't access the file system directly from say the JavaScript it's because of the sandbox that most modern browsers live in, otherwise people could attack your native directories from the front end languages. Your question is interesting as electron removes this sandboxing in a sophisticated esk manner, which is necessary as it's used for building desktop apps with chromium.
These days the most obvious solution would be to use some form of back end language and to create a web server that has direct access to the native directories around it. Node, PhP, GoLang and many other populatr backend languages can parse a directory of files and then interpolate those into the frontend code which is the most common method.
The other popular method at the moment is to create API's which is just a fancy web server with a queryable end point that then executes code against our web server and provides back a list of such items. You could then for instance take the items and then print those out using javascript.
Reference directories method in php:
http://php.net/manual/en/ref.dir.php
List contents of directory in nodejs:
https://code-maven.com/list-content-of-directory-with-nodejs
The best place to really start with the easiest route to understand more would be to start a backend language in either node or php, with php being the simpler of the two.
https://www.w3schools.com/php/
First you need to get your file list from server side. then you can use a code like following:
var imageList = //your image list as an array of urls;
var imageNumber = Math.random() * imageList.length; //gives you a random number in the range of imageList's size
var imageToLoad = new Image();
imageToLoad.addEventListener("load", function(){
console.log( "image is loading" );
$('#my-container').append(this); //in this case this will return image dom
});
imageToLoad.src = imageList[imageNumber];
this will add image to a container with id 'my-container' its just an example you can do anything you want using 'this'
So after much help and guidance from the community, I have figured out the answer! To clarify my process in extreme detail, here is what I did to achieve the desired outcome:
Create the page as a .php file instead of a .html file (in my case, index.php). If you are using notepad to create the file, make sure you change the file extension to .php, the encoding to UTF-8, and save file type as "All Files". As I understand it, PHP can pick the file at random but cannot pass this info to a static HTML page.
Place this block of code into the webpage where the image should show. Currently, it is set up to reference a folder named, "images" out of the root directory (aka mysite.com/images/). This can be changed by modifying the text between the apostrophes after $imagesDir. All other html markup on the page will work correctly if it is outside of the php code block.
Code Block:
<?php
$imagesDir = 'images/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)];
echo "<img src='$randomImage'>";
?>
Thank you #bardizba for the code! Although there may be less resource intensive ways to write this, my situation was a bit different because the file names in the directory did not follow a naming convention and there was a mix of file types (jpg, gif, etc.)
Thanks again to everyone that helped me out!

loading a external content so that searchable by Google for SEO purposes

I'm working on a project where we'd like to load external content onto a customers site. The main requirements are that we'd like the customer to have as simple of an include as possible (like a one-line link similar to Doubleclick) and would preferably not have to be involved in any server-side language. The two proposed ways of doing this were an iframe or loading a javascript file that document.write's out the content.
We looked more at the latter since it seemed to produce more reliable legibility and simplicity for the end user - a single line of Javascript. We have been hit with the reality that this will be indexed unpredictably by Google. I have read most of the posts on this topic regarding javascript and indexing (for example http://www.seroundtable.com/google-ajax-execute-15169.html, https://twitter.com/mattcutts/status/131425949597179904). Currenlty we have (for example):
<html>
<body>
<div class='main-container'>
<script src='http://www.other.com/page.js'></script>
</div>
</body>
</html>
and
// at http://www.other.com/page.js
document.write('blue fish and green grass');
but it looks like google indexes this type of content only sometimes based upon 'Fetch As Google' used in Google's webmaster tools. Since it does sometimes work, I know it's possible for this indexing to be ok. More specifically, if we isolate our content to something like the above and remove extraneous content, it will index it each time (as opposed to the EXACT SAME Javascript in a regular customer html page). If we have our content in a customer's html file it doesn't seem to get indexed.
What would be a better option to ensure that Google has indexed the content (remote isn't any better)? Ideas I have tried / come across would be to load a remote file in for example PHP, something like:
echo file_get_contents('http://www.other.com/page');
This is obviously blocking but possibly not a deal-breaker.
Given the above requirements, would there be any other solution?
thx
This is a common problem and I've created a JS plugin that you can use to solve this.
Url: https://github.com/kubrickology/Logical-escaped_fragment
Make sure to use the: __init() function instead of standard DOM ready functions and you know for sure that Google is able to index.

tracking a javascript found in pagesource

ive tried everything i cud to figure this out, but i cannot track a piece of javascript in a webpage
so, just to give you some context even though my problem is not related to just this scenario. it depends on a much bigger spectrum.
Anyway, im developing on sugarCRM and im trying to edit the default onclick behavior of a slot in calendar module (you dont need to understand this to help me, so please keep reading). when i click on a slot, a modal dialog window opens that lets me log a meeting or a call.
So i tracked down the javascript behind this. ive used firebug and chrome, and they both give a list of all the JS files that are being used on a given webpage
for example i search for "SUGAR.collection" and firebug tells me its located in a file named "sugar_field_grp.js?v=FVh1Z-v5nA6bYov7-aFFqQ" i can see this piece of code resides in sugar_field_grp.js,
but the code im trying to change resides in "index.php?module=Calendar&action=index&parentTab=Activities", firebug actually tells me this is the file that has the javascript i want to change.
I can also right click view page source and i can see that piece of code inside the script tag. so considering this piece of code doesnt reside in a JS file, i cannot change it, its generated at runtime (i think) but there must be some source, there must be a file thats telling sugarCRM to generate this code
tl;dr how to track down a piece of javascript code that resides on pagesource and theres no JS file specified by firebug or chrome save for index.php (this file doesnt have that javascript either)
i know its been a long post
thanks for reading
Learn how to search for strings in files on disk on your machine.
On Linux, MacOS and most unixen the go-to tool for this is grep. This applies to any programming language you work with. For your case simply cd into the directory of your source code and do:
grep -r SUGAR.collection .
If you're using git as your source control tool then git grep is much faster.
On Windows there are various GUI tools you can use to search for text in files. Just google: grep for windows.
If you're using an IDE then just your IDE's find-in-files functionality.
To track down specific code using Chrome / Webkit go through the following two steps:
Client:
1. Search all static text sources
Open the Dev Panel using CTRL + SHIFT + I
Hit CTRL + SHIFT + F for a global search dialog to pop up
Right next to it you can set pretty printing of the JS code to on: button { }
Enter your search term or terms using regular expressions
Optional: Decide if you need a case insensitive search which has a greater searchspace and takes longer
Example:
2. Search the dynamic user-DOM contents
Go to the Tab 'Elements' hit CTRL + F.
Enter your search term (This will also search iframes, svg's etc... within the parent DOM)
3. Recommended:
Cross-reference the results of step 1. and step 2.
If a given string is present in both the DOM and the static sources, then you can assume that the content is not programmatically created on the client-side.
Server:
Many projects perform a media bundling step prior to content-delivery. They pack web-resources into the main file (e.g. index.php) to save HTTP roundtrips.
Use sourcemaps / and or search the entire codebase for a salient static string or a salient keyword near the static string to locate the original source files.
Searching files:
Locally, I generally use the rapid index, and heuristic search of JetBrain's IDE's (IDEA, PHPStorm,...) and Sublime. The grep-command tool can definitely not compete here in terms of performance. On Windows I additionally use Totalcommander and its archive/regex finding abilities.
When quickly looking up code on the server you may use something like:
grep -r -C10 --color=always 'keyword1|keyword2' htdocs/ | less -R
which will also provide you with line-context. two caveats: you may want to filter out binaries first and symlinks outside the scope will be ignored.

Where to put JavaScript configuration functions?

What is the general developer opinion on including javascript code on the file instead of including it on the script tag.
So we all agree that jquery needs to be included with a script file, like below:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"
type="text/javascript"></script>
My question is, in order to get functions on a page that is not on all pages of a site. Do we include the functions like below in the same page or in a global include file like above called mysite.js.
$(document).ready(function(){
$(".clickme").click(function(event){
alert("Thanks for visiting!");
});
});
ok. So the question is: if the code above is going to be called in every class="clickme" on a specific pages, and you have the ability to call it either from an include separate file called mysite.js or in the content of the page. Which way will you go?
Arguments are:
If you include it on the page you will only call it from those specific pages that the js functionality is needed.
Or you include it as a file, which the browser cached, but then jquery will have to spend x ms to know that that function is not trigger on a page without "clickme" class in it.
EDIT 1:
Ok. One point that I want to make sure people address is what is the effect of having the document.ready function called things that does not exist in the page, will that trigger any type of delay on the browser? Is that a significant impact?
First of all - $("#clickme") will find the id="clickme" not class="clickme". You'd want $(".clickme") if you were looking for classes.
I (try to) never put any actual JavaScript code inside my XHTML documents, unless I'm working on testing something on a page quickly. I always link to an external JS file to load the functionality I want. Browsers without JS (like web crawlers) will not load these files, and it makes your code look much cleaner to the "view source".
If I need a bit of functionality only on one page - it sometimes gets its own include file. It all depends on how much functionality / slow selectors it uses. Just because you put your JS in an external JS file doesn't mean you need to include it on every page.
The main reason I use this practice - if I need to change some JavaScript code, it will all be in the same place, and change site wide.
As far as the question about performance goes- Some selectors take a lot of time, but most of them (especially those that deal with ID) are very quick. Searching for a selector that doesn't exist is a waste of time, but when you put that up against the wasted time of a second script HTTP request (which blocks the DOM from being ready btw), searching for an empty selector will generally win as being the lesser of the two evils. jQuery 1.3 Performace Notes and SlickSpeed will hopefully help you decide on how many MS you really are losing to searching for a class.
I tend to use an external file so if a change is needed it is done in one place for all pages, rather than x changes on x pages.
Also if you leave the project and someone else has to take over, it can be a massive pain to dig around the project trying to find some inline js.
My personal preference is
completely global functions, plugins and utilities - in a separate JavaScript file and referenced in each page (much like the jQuery file)
specific page functionality - in a separate JavaScript file and only referenced in the page it is needed for
Remember that you can also minify and gzip the files too.
I'm a firm believer of Unobtrusive JavaScript and therefore try to avoid having any JavaScript code in with the markup, even if the JavaScript is in it's own script block.
I agreed to never have code in your HTML page. In ASP.net I programmatically have added a check for each page to see if it has a same name javascript file.
Eg. MyPage.aspx will look for a MyPage.aspx.js
For my MVC master page I have this code to add a javascript link:
// Add Each page's javascript file
if (Page.ViewContext.View is WebFormView)
{
WebFormView view = Page.ViewContext.View as WebFormView;
string shortUrl = view.ViewPath + ".js";
if (File.Exists(Server.MapPath(shortUrl)))
{
_clientScriptIncludes["PageJavascript"] = Page.ResolveUrl(shortUrl);
}
}
This works well because:
It is automagically included in my files
The .js file lives alongside the page itself
Sorry if this doesn't apply to your language/coding style.

Categories

Resources