[英]Running a javascript function that is in an external .js file from within the script? (attached by src=) Using PHP
[英]Update Javascript variables within external .js using PHP?
我正在嘗試創建一個我可以從其他域引用的Javascript文件,該文件將允許更改用戶頁面的外觀。
例如,將在www.userwebsite.com上引用javascript文件(www.mywebsite.com/123.js),其中可能包含以下內容:
var thebody = document.getElementsByTagName('body')[0];
var newdiv = document.createElement('div');
var txtNode = document.createTextNode("Hello. This is a new node.");
var divIdName = "mydiv";
var csslink = "http://www.anotherwebsite.com/style.css";
var newcss = document.createElement('link');
newcss.setAttribute('href',csslink);
newcss.setAttribute('rel','stylesheet');
newcss.setAttribute('type','text/css');
newdiv.setAttribute('id',divIdName);
newdiv.appendChild(txtNode);
thebody.appendChild(newdiv);
thebody.appendChild(newcss);
它將插入對用戶網站上托管的CSS文件的引用,並使用文本節點“ Hello。這是一個新節點”向DOM添加新的div。
我希望用戶能夠登錄到CMS(我將構建),以便他們可以更改打印到頁面上的文本,而不必更改我提供給他們的Javascript文件。 CMS將托管在我的網站上。
最佳做法是什么?
顯然,我可以遠程編輯javascript文件,而無需用戶進行任何更改-但這是更新腳本的最佳方法嗎?
我正在考慮在javascript中有一個Ajax請求,該請求從php文件檢索輸出,該文件引用了mysql數據庫,並帶有用戶想要更改的文本-但是,相同的原始策略意味着這是不可能的。
謝謝
您不需要使用AJAX來檢索PHP輸出; 使客戶端在其頁面上添加<script />
標記,並將src
屬性設置為您的PHP輸出; 只要確保您的腳本發出有效的JavaScript。
由於您的Web服務器現在認為它在PHP領域而不是JS資產中,因此請確保發出正確的頁面標題; MIME類型很快就會過期。
header('Content-Type: application/x-javascript');
header('Last-Modified: Mon, 03 Sep 2012 22:33:44 GMT');
此外,請注意腳本將在不可靠且“敵對”的環境中執行。您應盡量減少JavaScript腳本聲明的全局變量的數量,以減輕沖突的風險。 最簡單的方法是將代碼包裝在IIFE中。
// Look ma, no global variables!
(function () {
var thebody = document.getElementsByTagName('body')[0];
var newdiv = document.createElement('div');
var txtNode = document.createTextNode("Hello. This is a new node.");
var divIdName = "mydiv";
var csslink = "http://www.anotherwebsite.com/style.css";
var newcss = document.createElement('link');
newcss.setAttribute('href',csslink);
newcss.setAttribute('rel','stylesheet');
newcss.setAttribute('type','text/css');
newdiv.setAttribute('id',divIdName);
newdiv.appendChild(txtNode);
thebody.appendChild(newdiv);
thebody.appendChild(newcss);
}());
您還應該考慮為CSS類,元素ID等添加前綴,以最大程度地減少與主機命名方案的沖突。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.