How to insert .js file reference to multiple html files
I'm working on a new website for my company, and we need to transfer hundreds of .html files to the new site. These .html do not currently contain any Google Analytics information, but I want to take this opportunity to add a reference to the .js file where the GA is 开发者_高级运维stored.
My question is: how can I add the .js reference to these hundreds of files quickly and easily, without having it edit each one?
I'm guessing that there is either a application that can parse hundreds of HTML files, identify a specific part of that file (such as the <head>
element) and automatically insert new text following it (e.g. <script type="text/javascript" src="script.js">
).
I've not been able to find any such software, and by typing this question there are no "questions with similar titles" or "similar questions" found here.
Any ideas?
There are lots of suggestions to do a search and replace, which will work. But the proper approach is to leverage whatever web platform you are using, and create a shared layout for the files that share a common design. Then, your common includes go there.
Otherwise, the next time Google changes their include code, or you decide to add a new .js library, or change anything else across the board, you will be doing this all over again. And it gets harder each time.
Also, you do not want to insert the include after the <head>
tag, you want it before the closing </body>
tag, so it does not stall the loading of the rest of the page.
I think Notepad++ or Dreamweaver would be able to do what you're looking for. I believe you can do a find/replace by directories - and/or multiple files. You could have it find the tag and then put the reference right after the head tag.
Open all of your files you want to change in a text editor with some sort of multiple-file management ability (TextMate, Coda, even XCode, Notepad++ etc.) then do a global find and use the "replace in project" (or similarly name).
Find the closing body
tag, and replace it with the javascript you want and the closing body
tag.
Find: </body>
Replace: <script src="somescript.js" type="text/javascript"></script></body>
You can include the following function in you global javascript file:
function insertGACode(){
var gaCode = document.createElement('script');
document.body.appendChild(gaCode);
gaCode.innerHTML = "GA CODE HERE";
}
Run it whenever the page loads.
Even sed would do you here.
sed -i.bak 's/</head>/<script type="text/javascript" src="script.js"></head>/' *.html
精彩评论